如何动态计算数据库中的行数? [英] How to count the number of rows in database dynamically?
问题描述
下面的php代码是一种计算特定表中行数的简单方法,但是只有刷新页面时,才能注意到行的任何增加或减少.因此,有什么方法可以使用jQuery/ajax来动态显示数据库表中的行数,而无需刷新页面和任何单击功能.
The php code below is a simple way to count number of rows in a certain table, but any increase or decrease in rows can only be noticed when page is refreshed. So is there any way using jQuery/ajax which can show the number of rows in database table dynamically without refreshing the page and without any click function.
html.php
$sql=$db->prepare("SELECT * FROM table WHERE selector=:selector");
$sql->execute(array(':selector'=>$selector));
$count=$sql->rowCount();
echo $count;
推荐答案
count.php
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);
将以下脚本添加到索引文件
Add following script to you index file
<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,则可以尝试:
If you don't want to use Jquery than you can try :
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事件
And add onload event on your body tag
<body onload="setTimeout(ajaxcall, 3000)" >
或者您可以通过单击某些按钮来调用ajax
or you can call ajax on some button click
<button onclick="setTimeout(ajaxcall, 3000)">clickme</button>
这篇关于如何动态计算数据库中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!