Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

anyone knows why?

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading