[英]Get count of Mysql rows in PHP
在下面的代碼中,當我var_dump($result)
我可以看到我想要的數據在其中...但是我仍然無法獲取它。
碼:
try {
$query = new dbquery(Connection::make($dbconfig['dbinfo']));
$count = $query->runSQL("select count(*) from table_name");
$result = $count->fetchAll();
var_dump($result);
echo $result[0];
echo $result[1];
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
SQL:
public function runSQL($sql, $params = NULL) {
//Prepares the SQL Statement you pass through
$statement = $this->pdo->prepare($sql);
//Binds the Parameters I pass through on execute, so no need for seperate $statement->bindParam()
$statement->execute($params);
//Returns the statement.
return $statement;
}
var_dump的輸出:
array(1) { [0]=> array(2) { ["count(*)"]=> string(1) "3" [0]=> string(1) "3" } } Array
這是我需要的["count(*)]
鍵,值3
我已經嘗試了以下方法,但沒有一個給我正確的價值:
echo $result[0];
echo $result[1];
echo $result['count(*)'];
誰能告訴我我要去哪里錯了,我只想知道行數。
結果是您將數組放入數組中。 您可以執行以下操作:
echo $result[0][0];
要么
echo $result[0]['count(*)'];
請注意 ,在查詢中進行別名處理是一個好習慣,以提高可讀性。 例如, COUNT(*)
可以別名為total_count
:
$count = $query->runSQL("select count(*) AS total_count from table_name");
現在,您可以按以下方式訪問總行數:
echo $result[0]['total_count'];
在僅返回1行(COUNT,SUM或任何組函數)的情況下,您需要避免使用fetchAll
您可以使用
echo $result[0][0];
要么
$result = $count->fetchOne(); #or $count->fetch(); read the docs to the right method
echo $result[0];
獲取行數的SQL命令是
select count(*) as alias from table_name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.