Home why the while loop runs once?
Reply: 1

why the while loop runs once?

ahmed nader
ahmed nader Published in 2018-01-12 21:32:16Z

the following code is only running once , while the number of times it should run is 4 , any help ?



header("Content-Type: application/json");


if(isset($_GET["m"])) {

    $dirname = "images/main/";
    $arr = array();

    $conn = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);

    if(!$conn) {
        echo "Error connecting to database";
    if($stmt = $conn->prepare("SELECT name_ FROM projects")) {
        $result = $stmt->get_result();
        if($result->num_rows == 0) {
            echo "No Projects";
        }else {
            while ($row = $result->fetch_assoc()) {
                $dirname = $dirname . $row["name_"] . "/";
                $images = glob($dirname . "*.*", GLOB_BRACE);
                foreach($images as $image) {
                    echo $row["name_"];
                    echo$result->num_rows;  // returns 4 !!!!
                    $image = base64_encode($image);
                    //$arr[] = $image;
                    array_push($arr, $image);
                    $image = "";
            echo json_encode($arr);  // returns 1 json row oonly




num rows return 4 so why it runs or loops for one time only ?

I am trying to get images from images folder to echo it back


according to jhilgeman's answer I added this part to the end of foreach:

$dirname = "images/main/";
jhilgeman Reply to 2018-01-12 21:42:52Z

If I had to guess, I'd say that it's looping correctly, but the problem is this line:

$dirname = $dirname . $row["name_"] . "/";

Each time you loop, you're APPENDING the $row["name"] value to whatever $dirname is. So let's say that you get 4 rows back like this:


At the beginning of the loop, let's say $dirname is just "/images/". So the first loop would change $dirname to be:


Then the second loop would change it to be:


The third loop would then make it:


And finally the fourth loop:


So unless you're expecting the $dirname to be appended that way, you probably want to instead REPLACE $dirname instead of appending to it each time.

Try this instead for your loop:

while ($row = $result->fetch_assoc()) {
  $images_dirname = $dirname . $row["name_"] . "/";
  $images = glob($images_dirname . "*.*", GLOB_BRACE);

  foreach($images as $image) {
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.347141 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO