Search code examples
phpmysqlsqlfor-loop

My for loop only allows one post to be displayed, over and over again



    
  /* To sort the id and limit the post by 40 */
  $sql = "SELECT * FROM requests"; 
  $result = $conn->query($sql);
  $sqlall= "SELECT * FROM requests ";
  $resultall = $conn->query($sqlall);
     
  $i = 0;
     
  if ($result->num_rows > 0) {  
    
      // Output data of each row
      $idarray= array();
      while($row = $result->fetch_assoc()) {
          echo "<br>";  
          
          // Create an array to store the
          // id of the blogs        
          array_push($idarray,$row['id']); 
      } 
  }
  else {
      echo "0 results";
  }
?>
          <?php 
            for($x = 1; $x < 40; $x++) {
              // This is the loop to display all the stored blog posts
              if(isset($x)) {
                $query = mysqli_query(
$conn,"SELECT * FROM `requests`");
                  
                $res = mysqli_fetch_array($query);
                $email1 = $res['email1'];
                $msg1= $res['msg1'];
                $subject1 = $res['subject1'];
                $name1 = $res['name1'];
                $id = $res['id'];


                  
            

the output is 40 cards reading data from the first row in my database. can anyone help? I'm using xampp. This code is to show the loop, but if anyone wants the full code is here


Solution

  • You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests 40 more times, and always extract the same first row. You never use the ID to change the query.

    But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:

    $sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
    $result = $conn->query($sql);
    
    while ($res = $result->fetch_assoc()) {
      $email1 = $res['email1'];
      $msg1 = $res['msg1'];
      $subject1 = $res['subject1'];
      $name1 = $res['name1'];
      $id = $res['id'];
    
      //example output, just for demo:
      echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
    }
    

    Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html