嘗試使用 while($result != EOF) 或 while($row != false) 但未在循環內獲取下一行,導致死循環或邏輯錯誤。EOF 是文件操作常量,不適用於 MySQL 結果集。
使用 mysql_fetch_array()(或 mysql_fetch_assoc())在 while 條件中直接賦值,該函數在無更多行時返回 false,自動結束循環:
<?php
$sql = "SELECT * FROM table1";
$result = mysql_query($sql);
if (!$result) {
die("查詢失敗: " . mysql_error());
}
while ($row = mysql_fetch_assoc($result)) {
// $row 為關聯數組,包含當前行所有字段
$nowdt = $row['ac_exp_dt'];
$nowmon = $row['ac_exp_mon'];
$nowyr = $row['ac_exp_year'];
$daydiff = (strtotime("$nowyr-$nowmon-$nowdt") - strtotime(date("Y-m-d"))) / 86400;
$status = ($daydiff < 0) ? 0 : 1;
$uid = $row['indexuid'];
mysql_query("UPDATE CUSTOMERS SET Current_Status=$status WHERE indexuid=$uid");
}
mysql_free_result($result);
?>
mysql_fetch_assoc 每次調用移動內部指針到下一行,直到返回 false。mysql_data_seek($result, 0) 重置指針,或將數據先存入數組。mysql_* 函數自 PHP 5.5 棄用,PHP 7.0 移除。新代碼請使用 mysqli 或 PDO,邏輯相同但更安全。$stmt = $pdo->query("SELECT * FROM table1");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// 業務邏輯
}