如何每隔几秒查询一次数据库?

时间:2012-11-20 23:00:19

标签: php mysql database

所以,这是我的代码:

<?php
//Connect to the database
include("config.php");

//Query the database and get the count  
$result = mysql_query("SELECT * FROM ads");  
$num_rows = mysql_num_rows($result);  
?>

如何制作它以便每隔几秒查询一次数据库?

1 个答案:

答案 0 :(得分:4)

单独保存PHP脚本(在我的示例下面的thescript.php)

<?php

  //Connect to the database
  include("config.php");

  //Query the database and get the count 
  $q = mysql_query("SELECT count(*) as num FROM ads");
  $count = mysql_fetch_result($q,0,'num');
  echo $count; 

?>

然后在home.php文件中使用AJAX / javascript / jQuery:

 <script>
    $(function(){
      function loadNum()
      {  
        $('h1.countdown').load('thescript.php');
        setTimeout(loadNum, 5000); // makes it reload every 5 sec
      }
      loadNum(); // start the process...
    });
 </script>