我有一個問題,我無法弄清楚太久。基本上我有一個帶有用戶名的表(表中的 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,]
有誰知道為什么?
uj5u.com熱心網友回復:
原因是因為您從未$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);
}
uj5u.com熱心網友回復:
另一種方法是將檔案名存盤在一個陣列中,以名稱作為索引(同時確保每次都將影像名稱清空)...
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 子句與 mysqli 準備好的陳述句),您可以在一次執行中獲取已知用戶和檔案名的串列......
$stmt = $db->prepare("SELECT username, file_name
FROM images
WHERE username in...
只需遍歷結果并將它們添加到陣列中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390707.html
