1

I have a problem with a while statement in PHP and mysql that I have been trying to figure out for ages, I hope you can help me.

I have a while statement, and inside that I have two if statements. It seems to be working, except it displays the first entry in the array only, multiple times.

   <?php
      $i=1;
      while($i<5){

      if ($data_review_list['review'] > 4){ 
           echo "<img src=\"images/good.png\" />\n"; 
      } 

      else{ 
           echo "<img src=\"images/bad.png\"  />\n";
      }
      echo $data_review_user['user_name']; 

      echo $data_review_list['review_msg']; 

      $i++;
     }
     ?>

I have put ($i<5) as using ($i!=0) was give me a long list of the first entry. This gives me the first entry 5 times.

What am I doing wrong? How can I get the second etc entry to display?

Thank you!

1
  • Whould you post how you query data from database. Commented Apr 16, 2011 at 23:37

3 Answers 3

2

Although you're updating $i each time through the loop, you're never looking at $data_review_list[$i]. What does $data_review_list look like? Use this code to examine the array:

var_dump($data_review_list);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. using the var_dump really helped as I found out that I was just querying the first entry. Changing my fetch_array solved my problem!
0

I don't know whether you use mysql or mysqli, but i'll assume you use mysqli for this example. Also let's assume that the query you are querying in mysql has LIMIT 5 in the end.

<?php while($data = $result->fetch_assoc()) {
    if($data['review'] > 4) {
        echo "<img src=\"images/good.png\" />\n"; 
    } else { 
        echo "<img src=\"images/bad.png\"  />\n";
    }

    echo $data['user_name'];
    echo $data['review_msg'];
} ?>

This would fetch each of the 5 rows in the while statement.

1 Comment

Thanks, I am using mysql. Turns out I was fetching the array incorrectly.
0

At a guess it should look like this (i am making a few assumptions about your data structure here)

<?php
          $i=1;
          while($i<5){

          if ($data_review_list[$i]['review'] > 4){ 
               echo "<img src=\"images/good.png\" />\n"; 
          } 

          else{ 
               echo "<img src=\"images/bad.png\"  />\n";
          }
          echo $data_review_user[$i]['user_name']; 

          echo $data_review_list[$i]['review_msg']; 

          $i++;
         }
         ?>

1 Comment

Thank you, this helps me in my search for knowledge, but with this problem I was fetching my array incorrectly.

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.