简体   繁体   中英

prepared statement in the loop

I have a problem that i cant figure out for too long. Basically I have table with usernames (1 unique username in the table) with 1 respective image file. Some of users have image file and some dont. usernames are stored in the array $Users[]. I am trying to fetch filenames of images for each user using:

$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;
    }

however this has annoying behavior. Say as code loops through, if user User[0] has $ImgFileName related to it, but User[1], User[2] etc doesnt, then $ImgFileName is used of the last user with available image, instead of null. This happens until some user in the loop again has image filename in the table. So if i print $imageURL[] array after loops goes through, it looks smth like:

$Users[]=[user1,user2,user3,user4,user5]
$imageURL[]=[img001.png,img001.png,img001.png,img231.png,img124.png,img124.png]

instead of

$Users[]=[user1,user2,user3,user4,user5]
$imageURL[]=[img001.png,,,img231.png,img124.png,]

anyone knows why?

The reason why is because you never reset $ImgFileName inside the loop.

Put $ImgFileName = null; inside the loop.

You can also unset the variable, which will result in the same outcome.

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);
}

An alternative is to store the file name in an array with the name as the index (along with ensuring that the image name is blanked out each time)...

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;
}

If you also combine this with using in (from How do you use IN clauses with mysqli prepared statements ) you could just fetch a list of the known users and filenames in one execution...

$stmt = $db->prepare("SELECT username, file_name
                       FROM images 
                       WHERE username in...

just loop through the results and add them into an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM