[英]prepared statement in the loop
我有一個問題,我無法弄清楚太久。 基本上我有一個帶有用戶名的表(表中的1個唯一用戶名)和1個相應的圖像文件。 有些用戶有圖像文件,有些沒有。 用戶名存儲在數組 $Users[] 中。 我正在嘗試使用以下方法獲取每個用戶的圖像文件名:
$stmt = $db->prepare("SELECT file_name FROM images WHERE BINARY username=?");
for($temp1=0; $temp1<count($Users); $temp1++){
$stmt->bind_param("s", $Users[$temp1]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ImgFileName);
$stmt->fetch();
$imageURL[$temp1]=$ImgFileName;
}
然而,這有令人討厭的行為。 假設代碼循環通過,如果用戶 User[0] 具有與其相關的 $ImgFileName,但 User[1]、User[2] 等沒有,則 $ImgFileName 用於最后一個具有可用圖像的用戶,而不是 null。 這種情況會發生,直到循環中的某個用戶再次在表中具有圖像文件名。 因此,如果我在循環通過后打印 $imageURL[] 數組,它看起來像:
$Users[]=[user1,user2,user3,user4,user5]
$imageURL[]=[img001.png,img001.png,img001.png,img231.png,img124.png,img124.png]
代替
$Users[]=[user1,user2,user3,user4,user5]
$imageURL[]=[img001.png,,,img231.png,img124.png,]
有誰知道為什么?
原因是您從未在循環內重置$ImgFileName
。
把$ImgFileName = null;
循環內。
您也可以取消設置變量,這將導致相同的結果。
for($temp1=0; $temp1<count($Users); $temp1++){
$stmt->bind_param("s", $Users[$temp1]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ImgFileName);
$stmt->fetch();
$imageURL[$temp1]=$ImgFileName;
unset($ImgFileName);
}
另一種方法是將文件名存儲在一個數組中,並將名稱作為索引(同時確保圖像名稱每次都被空白)......
for($temp1=0; $temp1<count($Users); $temp1++){
$ImgFileName = '';
$userName = $Users[$temp1];
$stmt->bind_param("s", $userName);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ImgFileName);
$stmt->fetch();
$imageURL[$userName] = $ImgFileName;
}
如果您還將此與 using in
結合使用(來自How do you use IN clauses with mysqli Prepared statements )您可以在一次執行中獲取已知用戶和文件名的列表...
$stmt = $db->prepare("SELECT username, file_name
FROM images
WHERE username in...
只需遍歷結果並將它們添加到數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.