简体   繁体   English

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

[英]How to count the number of rows in database dynamically?

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. 下面的php代码是一种计算特定表中行数的简单方法,但是只有刷新页面时,才能注意到行的任何增加或减少。 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. 因此,有什么方法可以使用jQuery / ajax来动态显示数据库表中的行数,而无需刷新页面和任何单击功能。

html.php 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>

If you don't want to use Jquery than you can try : 如果您不想使用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>

And add onload event on your body tag 并在您的body标签上添加onload事件

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

or you can call ajax on some button click 或者您可以通过单击某些按钮来调用ajax

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

Try to make the sql query in a php function which is accessible through an url and returns json_encoded(num_of_rows). 尝试在可通过url访问并返回json_encoded(num_of_rows)的php函数中进行sql查询。 Then in your javascript you can get it through an ajax get request, specifying it is json, better to set in a function which is a onClick event on a button, which you will click to make the call without refreshing the pages, but just the target tag where your javascript function will put the result from the ajax. 然后在您的javascript中,您可以通过ajax get请求将其获取,将其指定为json,最好在一个按钮上设置onClick事件的函数中进行设置,您无需单击即可单击以进行调用,而无需刷新页面,但是target标记,您的javascript函数会将结果从ajax中放入。 Hope it is clear enough. 希望它足够清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM