回傳型別比較
| 函式 | 回傳型別 | 存取方式 |
mysql_fetch_array() | 陣列 (數值索引 + 關聯索引) | $row['col'] 或 $row[0] |
mysql_fetch_object() | 物件 (stdClass) | $row->col |
常見錯誤示範
// 錯誤:fetch_array 回傳陣列,不能用 -> 存取
while ($rs = mysql_fetch_array($result)) {
echo $rs->username; // Notice: Trying to get property of non-object
}
// 正確:用陣列語法
while ($rs = mysql_fetch_array($result)) {
echo $rs['username'];
}
// 錯誤:fetch_object 回傳物件,不能用 [] 存取
while ($rs = mysql_fetch_object($result)) {
echo $rs['username']; // Fatal error: Cannot use object as array
}
// 正確:用物件語法
while ($rs = mysql_fetch_object($result)) {
echo $rs->username;
}
選擇建議
- 習慣陣列操作、需數值索引 →
mysql_fetch_array()(或 mysqli_fetch_assoc() 只取關聯)。
- 偏好物件導向、程式碼可讀性 →
mysql_fetch_object()。
- 現代專案請改用 mysqli/PDO 同名函式,
mysql_* 已移除。