mysql_fetch_array() 讀取下一列,若結果集為空或已讀完,回傳 false。利用此特性可判斷是否有資料。
$sql = "SELECT * FROM abc";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if (empty($row)) {
echo "null"; // 無資料
} else {
echo "not null"; // 有資料,$row 已是第一列
// 可繼續 while 處理後續列
}
$row = mysql_fetch_array($result);
if (!$row) {
echo "null";
} else {
echo "not null";
}
// 錯誤!結果集為空時 mysql_fetch_array 回傳 false,觸發 die()
$row = mysql_fetch_array($result) or die(mysql_error());
後果:正常的空結果集會被誤判為錯誤,導致腳本異常終止。
ext/mysql 已於 PHP 7.0 移除,請改用 mysqli 或 PDO。$stmt = $mysqli->prepare("SELECT * FROM abc");
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
echo "null";
} else {
$row = $result->fetch_assoc();
echo "not null";
}
mysql_fetch_array() 回傳值直接判斷真偽。or die()。mysqli/PDO。