2012-05-03 74 views
-2

當我嘗試使用下面的代碼時,出現錯誤Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given運行MySQL查詢時出錯

include('config.php'); 

$con = mysql_connect($dbhost,$dbuser,$dbpasswd); 
if (!$con) 
    { 
     die('Could not connect: ' . mysql_error()); 
    } else { 
     mysql_select_db($dbname, $con); 
    } 
$date = getdate(); 
$result = mysql_query("SELECT * FROM '" . $table_prefix . "users' where user_regdate = '" . $date . "'"); 
$total = 0; 
while($row = mysql_fetch_array($result)) 
    { 
    $total++; 
    echo $row['username']; 
    echo "<br />"; 
    } 
+1

我不認爲你需要圍繞表名單引號。 –

回答

1

您引用了單引號'的表名。如果您引用它,請反引用。單引號僅用於MySQL中的字符串文字。這會導致查詢中出現語法錯誤。

$result = mysql_query("SELECT * FROM `" . $table_prefix . "users` where user_regdate = '" . $date . "'"); 

接下來,getdate()在PHP返回數組,而不是日期字符串,當其作爲字符串傳遞到查詢字Array提供查詢。相反,使用MySQL的本地日期函數來獲取今天的日期格式MySQL的預期(YYYY-MM-DD):評論後

編輯:

既然你有一個Unix時間戳,而不是日期列,創建日期的Unix時間戳:

where user_regdate = UNIX_TIMESTAMP(GETDATE()) 

一個小錯誤就mysql_query()呼叫檢查會發現錯誤的查詢源,確實是必要的,以防止你的腳本由致命的失敗。

$result = mysql_query("SELECT * FROM `" . $table_prefix . "users` where user_regdate = '" . $date . "'"); 
if (!$result) { 
    // query failed 
    echo mysql_error(); 
} 
else { 
    // all is well, proceed with fetch... 
} 

最後,我注意到你正在收集的行數爲$total++。這是不必要的(除非您正在執行一些我們沒有看到的更具體的邏輯),因爲該值可通過mysql_num_rows($result)獲得。

+0

好吧,'東西擺脫了錯誤。我從來沒有見過這些。但它仍然沒有結果。所以我的猜測是我的sql日期格式是一堆數字。 「1283216436」。我猜測$ date = date('Y-m-d');不提供我需要的這些數字。 – alexander7567

+0

好吧,我試圖用這個來修正這個$ result = mysql_query(「SELECT * FROM'」。$ table_prefix。「users' where user_regdate ='」。strtotime($ date)。「'」);.不過,我仍然得到1335931200的日期,當我需要1335973416. – alexander7567

+0

@ alexander7567不要在日期字符串中使用strtotime()。相反,只需使用'$ date = time();'來獲得時間戳。理想情況下,應該更改該列以保留適當的日期時間類型,而不是Unix時間戳。 –

0

您的查詢出錯了。從http://php.net/manual/en/function.mysql-query.php

mysql_query在成功時返回資源,錯誤時返回false。

+0

好吧,那是因爲。沒有我的下一個問題是我如何在mysql中搜索今天的日期。 – alexander7567

+0

@ alexander7567今天在mysql中你可以試試'select now()'它會在今天返回你的日期和時間。 –

0

因爲它返回0行檢查mysql_num_rows() include('config.php');

$con = mysql_connect($dbhost,$dbuser,$dbpasswd); 
if (!$con) 
    { 
     die('Could not connect: ' . mysql_error()); 
    } else { 
     mysql_select_db($dbname, $con); 
    } 
$date = getdate(); 
$result = mysql_query("SELECT * FROM '" . $table_prefix . "users' where user_regdate = '" . $date . "'"); 
$total = 0; 
if(mysql_num_rows($result)){ 
while($row = mysql_fetch_array($result)) 
    { 
    $total++; 
    echo $row['username']; 
    echo "<br />"; 
    } 
}