[PHP] Mysqli_stmt 之 fetch注意事項

這篇給自己留案底



如果使用PHP的mysqli_stmt
要注意在執行$stmt->excute()後

使用$stmt->fetch()需要在之前加上$stmt->store_result(),
如果沒有先store_result()可能會fetch不到結果。
e.g.
$stmt->excute();
$stmt->store_result();

$stmt->bind_param( $a, $b... );
while( $stmt->fetch() ) {
  ...
} // END of while()

使用$stmt->fetch_array(), $stmt->fetch_assoc(), $stmt->get_result()就不要加,
如果執行了store_result(),就會fetch不到而出現錯誤"call a member function on a non object",
e.g.
$stmt->excute();
// $stmt->store_result(); // you should not add this line

$fetch_result = $stmt->get_result();

while( $it = $fetch_result->fatch_assoc() ) {
  ...
} // END of while()

我猜store_result()應該是給fetch()專用的,會把結果移到fetch()的buffer裡去,
但是剩下的fetch方式可能是直接從connect接收回傳結果,
如果store_result()後就會從sql那邊得到NULL。

警惕之。

TAG: fetch, mysqli, mysqli_stmt

留言

這個網誌中的熱門文章

[Javascript] 利用Google Calendar api 存取 Google 行事曆

[滑鼠] 羅技G402 換微動