如何动态计算数据库中的行数?

时间:2016-03-03 05:47:07

标签: php jquery

下面的php代码是计算某个表中行数的简单方法,但只有在刷新页面时才能注意到行的任何增加或减少。那么有没有办法使用jQuery / ajax,它可以动态显示数据库表中的行数而无需刷新页面,也没有任何点击功能。

html.php

$sql=$db->prepare("SELECT * FROM table WHERE selector=:selector");
$sql->execute(array(':selector'=>$selector));
$count=$sql->rowCount();
echo $count;

2 个答案:

答案 0 :(得分:2)

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>

在你的身体标签上添加onload事件

 <body onload="setTimeout(ajaxcall, 3000)" >

或者您可以点击某个按钮调用ajax

<button onclick="setTimeout(ajaxcall, 3000)">clickme</button>

答案 1 :(得分:1)

尝试在php函数中进行sql查询,该函数可通过url访问并返回json_encoded(num_of_rows)。然后在你的javascript中你可以通过ajax get请求得到它,指定它是json,最好设置一个按钮上的onClick事件的函数,你将点击进行调用而不刷新页面,但只是目标标记,你的javascript函数将放置ajax的结果。希望它足够清楚。