[英]mysql COUNT(*) always returns 8
標題說明了一切。 我有以下代碼:
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
return $result;
}
似乎它應該是有史以來最簡單的函數,但結果始終返回8。
有任何想法嗎?
謝謝,喬希
您的函數返回mysql_query()
函數結果,這不是SQL查詢的結果。
您必須使用mysql_*
舊的PHP函數執行類似於mysql_fetch_assoc()
的mysql_*
。
PS:您現在應該使用PDO,不建議使用mysql_*
,這只是一個技巧;)
獲取結果中的記錄數
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) AS count FROM `".$table."`");
if (! $result) {
// throw exception
}
$row = mysql_fetch_assoc($result);
return $row['count'];
}
也。 如先前的響應者所指出的,您需要停止使用mysql_*
並開始使用mysqli_*
或PDO
。 適用於PDO的PHP文檔
mysql_query
返回資源: http : //php.net/manual/en/function.mysql-query.php
返回該值不會給您查詢結果。 您需要mysql_fetch_array()。
一個工作示例:
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
if($row = mysql_fetch_row($result)) {
return $row[0];
}
else {
return false;
}
}
嘗試使用mysql_fetch_array()
mysql_fetch_assoc()
或mysql_fetch_object()
獲得結果
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) AS count FROM `".$table."`");
if (! $result) {
// throw exception
}
$row = mysql_fetch_array($result);
return $row['count'];
}
希望對您有所幫助
您需要獲取查詢,而不返回mysql_query。
嘗試這個
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) as counts FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
$row =mysql_fetch_array($result) ;
return $row['counts'];
}
您最好使用mysql_num_rows,因為它不需要獲取任何數據,並且效率更高
public function getRows($table) {
$result = mysql_query("SELECT * FROM `".$table."`");
if (! $result) {
// throw exception
}
$rows = mysql_num_rows($result);
return $rows;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.