[英]How to count the number of rows in database dynamically?
下面的php代碼是一種計算特定表中行數的簡單方法,但是只有刷新頁面時,才能注意到行的任何增加或減少。 因此,有什么方法可以使用jQuery / ajax來動態顯示數據庫表中的行數,而無需刷新頁面和任何單擊功能。
html.php
$sql=$db->prepare("SELECT * FROM table WHERE selector=:selector");
$sql->execute(array(':selector'=>$selector));
$count=$sql->rowCount();
echo $count;
count.php
$sql=$db->prepare("SELECT * FROM table WHERE selector=:selector");
$sql->execute(array(':selector'=>$selector));
$count=$sql->rowCount();
$arr = array('count' => $count)
echo json_encode($arr);
將以下腳本添加到索引文件
<script>
$(document).ready(function() {
setInterval("ajaxcall()",2000);
});
function ajaxcall() {
$.ajax({
type: "GET",
url: "count.php"
success: function(response){
json_object = JSON.parse(response)
var count = json_object.count
/// set this count variable in element where you want to
/// display count
}
});
}
</script>
如果您不想使用Jquery,則可以嘗試:
function ajaxcall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
json_object = JSON.parse(xhttp.responseText)
var count = json_object.count
/// set this count variable in element where you want to
/// display count
}
};
xhttp.open("GET", "count.php", true);
xhttp.send();
setTimeout(ajaxcall, 1000)
}
</script>
並在您的body標簽上添加onload事件
<body onload="setTimeout(ajaxcall, 3000)" >
或者您可以通過單擊某些按鈕來調用ajax
<button onclick="setTimeout(ajaxcall, 3000)">clickme</button>
嘗試在可通過url訪問並返回json_encoded(num_of_rows)的php函數中進行sql查詢。 然后在您的javascript中,您可以通過ajax get請求將其獲取,將其指定為json,最好在一個按鈕上設置onClick事件的函數中進行設置,您無需單擊即可單擊以進行調用,而無需刷新頁面,但是target標記,您的javascript函數會將結果從ajax中放入。 希望它足夠清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.