0

i'm trying to display a while loop depending on the parameters in my for loop. for example, my for loop says to loop through 5 times, the data inside while loop should also be displayed 5 times. however, when i tested my code, the data inside while loop only displays once. i'm not sure if i did the iteration correctly. here is a snippet of my nested loop.

for($i=0; $i<$count; $i++){

            echo "COUNT: ".$i."<br>";
            while($data=mysqli_fetch_array($res)) { 
                echo "INSIDE WHILE".$i."<br>";
                }

        }

so if my $count = 3, the output of this code is

0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0

1

2

and what i want is for "INSIDE WHILE" to also be displayed between 1 and 2.

10
  • did you have the mysqli_query() code? Commented Mar 21, 2018 at 5:46
  • @RendiWahyudiMuliawan $res=mysqli_query($conn,$query); Commented Mar 21, 2018 at 5:48
  • Your while depends on the results of your query. If there are no more results to fetch, the while will not run again, regardless of how many times the for is run. Commented Mar 21, 2018 at 6:00
  • $query="SELECT * FROM products"; $res=mysqli_query($conn,$query); Commented Mar 21, 2018 at 6:01
  • while loop is ended in the first iteration. as it fetch all records in a single-shot. that's why 1 and 2 are having blank Commented Mar 21, 2018 at 6:03

2 Answers 2

2

Just add mysqli_data_seek after the while loop:

for($i=0; $i<$count; $i++){
    echo "COUNT: ".$i."<br>";
    while($data=mysqli_fetch_array($res)) { 
        echo "INSIDE WHILE".$i."<br>";
    }
    mysqli_data_seek($res, 0);
}
Sign up to request clarification or add additional context in comments.

Comments

0
$data=mysqli_fetch_array($res, MYSQLI_ASSOC);

for($i=0; $i<$count; $i++){
    echo "COUNT: ".$i."<br>";
    foreach ($data as $current_data){
          echo "INSIDE WHILE".$i."<br>";
          echo $current_data[name]; //name is the field name.
    }
}

You can move the fetch on top, so you don't have to reset the cursor of the fetch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.