我想算表中的行數,並認爲這是應該做的是正確的方法:庫MySQLi COUNT(*)始終返回1
$result = $db->query("SELECT COUNT(*) FROM `table`;");
$count = $result->num_rows;
但數總是返回(int)1
。如果我在phpMyAdmin中使用相同的查詢,我會得到正確的結果。它坐在一張桌子裏,所以我試着測試$count[0]
,但是它返回NULL
。
這樣做的正確方法是什麼?
我想算表中的行數,並認爲這是應該做的是正確的方法:庫MySQLi COUNT(*)始終返回1
$result = $db->query("SELECT COUNT(*) FROM `table`;");
$count = $result->num_rows;
但數總是返回(int)1
。如果我在phpMyAdmin中使用相同的查詢,我會得到正確的結果。它坐在一張桌子裏,所以我試着測試$count[0]
,但是它返回NULL
。
這樣做的正確方法是什麼?
你必須獲取一個記錄,它將包含COUNT()的結果
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
總是嘗試做一個關聯回來,你在多的情況下結果
想要的方式,您可以輕鬆獲取下面是一個例子
$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";
$result->close();
好奇你是什麼意思的多個案件的結果?使用case語句選擇多個計數? – 2012-08-02 14:47:09
$ result-> NUM_ROWS;只返回受查詢影響的行數。當你在表上執行COUNT(*),它只返回一行,所以你不能有其他結果大於1
不正確。 mysqli_result :: $ num_rows返回結果集的行數。 mysqli :: $ affected_rows返回查詢影響的行數。 – 2013-08-08 06:16:32
,我覺得這樣更易於閱讀:
$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
$result->free();
$mysqli->close();
echo "there are {$count} rows in the table";
這並不是說我有任何對陣陣......
這對我很好。
// Veh Pro Count
$query_tvp = "SELECT count(*) as total from submit";
if ($result_tvp = $mysqli->query("$query_tvp")) {
/* determine number of rows result set */
$total_tvp = $result_tvp->fetch_row();
$total_tvp = $total_tvp['0'];
/* close result set */
$result_tvp->close();
}
echo "Total: $total_tvp";
可以用'$ mysqli_result-> NUM_ROWS;'見 - http://php.net/manual/en/mysqli-result.num-rows.php – 2017-11-15 02:02:12