所以,這是我的代碼:如何每隔幾秒查詢一次數據庫?
<?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);
?>
我怎樣才能使它所以查詢的數據庫爲計數每隔幾秒鐘?
所以,這是我的代碼:如何每隔幾秒查詢一次數據庫?
<?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);
?>
我怎樣才能使它所以查詢的數據庫爲計數每隔幾秒鐘?
單獨保存你的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>
對不起,我不是一個非常有經驗的程序員。所以,'thescript.php'應該是我上面給出的代碼所在的文件(so,home.php)?另外,datacontainer DIV中需要什麼?謝謝。 –
datacontainer div將從PHP腳本中加載內容。只要腳本將其加載到HTML代碼中的現有元素中,就可以隨意命名它......並且對於AJAX解決方案,只需將上述所有代碼放在一個單獨的文件中,我稱之爲它thescript.php,但你可以想到更聰明的東西! :) – jtheman
謝謝!我會嘗試的。 –
你確定這是最好的解決方案?假設您想從瀏覽器/客戶端執行此操作,則可能每隔幾秒就會發出大量針對數據庫的請求。 –
這取決於。你想用$ num_rows做什麼?你把它扔掉了嗎?顯示它?給它發電子郵件? – slashingweapon
你爲什麼想要? – 2012-11-20 23:02:05