Search code examples
phpglob

PHP use glob() inside MySQLi while loop


On my website's dashboard, I use a while loop to retrieve data from a DB and echo each record. Inside this while loop, I use glob() to show all the images inside the specific folder, which is a column in my DB table, $record["folder"].

This is the code I use:

while($record = mysqli_fetch_array($result))

   {

            $directory = '../send-us-your-photos/media/'.$record['folder'];
            chdir($directory);
            $images = glob("*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
            foreach($images as $image) {
                echo '<div class="col-sm-4">
                        <img src="'.$directory.'/'.$image.'" />
                        <div>'.$image.'</div>                              
                      </div>'; 
            } 

   }

Now, the first record works fine and is showing the images in the specific folder. But the next records all show the same $image data but for a different folder.

So for example:

Record 1: folder 1 - shows image1.jpg

Record 2: folder 2 - tries to find same image1.jpg in folder 2

Record 3: folder 3 - tries to find same image1.jpg in folder 3

What I need:

Record 1: folder 1 - shows images in folder 1

Record 2: folder 2 - shows images in folder 2

Record 3: folder 3 - shows images in folder 3


How should I change my code so it shows the correct images in each record?


Solution

  • simply , don't change your directory , and use your directory path directly in glob function

    while($record = mysqli_fetch_array($result))
    {
        $directory = '../send-us-your-photos/media/'.$record['folder'];
        // chdir($directory);
        $images = glob($directory . "/*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
        foreach($images as $image) {
            echo '<div class="col-sm-4">
            <img src="'.$directory.'/'.$image.'" />
            <div>'.$image.'</div>                              
            </div>'; 
        } 
    }