在PHP中,resources從某些函數返回,以便他們可以傳遞給其他相關功能。示例包括數據庫連接,數據庫查詢結果,文件句柄等。
根據mysql_query()
上的文檔,SELECT查詢返回資源。您可以獲取該資源並將其傳遞給許多不同的功能。要檢索行數,可以使用mysql_num_rows()
來檢索查詢結果,可以使用mysql_fetch_array()
,mysql_fetch_assoc()
或mysql_fetch_object()
。
與數據庫的處理結果將會是這個樣子正常模式:
$result = mysql_query("SELECT * FROM persons"); // run query against database
$count = mysql_num_rows($result); // retrieve a count of the rows in the previous query
while ($row = mysql_fetch_assoc($result)) { // loop through all the rows in the resultset
// use $row['column_name'] to access columns in your resultset
}
從你上面的例子:
$result = mysql_query("SELECT COUNT(*) AS num FROM persons"); // run query against db
$row = mysql_fetch_assoc($result); // retrieve the 1 (and only) row
$count = $row['num']; // we needed to alias the COUNT(*) column as `num`