Jackson Jackson - 4 months ago 7
PHP Question

PHP: glob in foreach multiplies with each row?

This is a bit confusing and hard to explain but I will try my best to explain it.

Basically, I have a directory of images (

test
) which holds all the images for my products.

The images look like this:

999999999Image1.jpg
999999999Image2.jpg
999999999Image3.jpg
999999999Image4.jpg
999999999Image5.jpg

555555555Image6.jpg
555555555Image7.jpg
555555555Image8.jpg
555555555Image9.jpg
555555555Image10.jpg

etc etc...


The numbers before Image is a field in MYSQL database called
STOCK
.

Now, I'm trying to use
glob()
to display the images for each item in mysql database like so:

while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

$STOCK = $row['STOCK'];

foreach(glob('test/'.$STOCK.'*') as $image) {

if($image != ""){
$pic_list2 .= '<img data-src="'.$image.'" class="smallImg" width="57" height="43" data-id="'.$STOCK.'" data-details="'.$ADVERT_DESCRIPTION_main.'" data-name="'.$MAKE2.' '.$MODEL2.' '.$DERIVATIVE2.'" data-price="'.$PRICE2.'" src="'.$image.'" alt="" />';

}
else{
$pic_list2 = '';
}
}

/////rest of my code..../////

}


However, when I run my code, I get a very strange output...

The issue that I have is that with each output of MYSQL result, the images that being found by glob() is being added to the next result too! So, its like the image of the first result are being added to the next result and then the images of first result and the second results are being added to the third result and so on so forth...

I hope this makes sense and someone could point me in the right direction.

Any help would be appreciated.

Answer

I suggest:

while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

    $STOCK = $row['STOCK'];

    $pic_list2 = ''; // you need this line also here !! only change

    foreach(glob('test/'.$STOCK.'*') as $image) {   

        if($image != ""){
            $pic_list2 .= '<img data-src="'.$image.'" class="smallImg" width="57" height="43" data-id="'.$STOCK.'" data-details="'.$ADVERT_DESCRIPTION_main.'" data-name="'.$MAKE2.' '.$MODEL2.' '.$DERIVATIVE2.'" data-price="'.$PRICE2.'" src="'.$image.'" alt="" />';

        }
        else{
            $pic_list2 = ''; 
        } 
    }

    /////rest of my code..../////

}
Comments