【问题标题】:My for loop only allows one post to be displayed, over and over again我的 for 循环只允许显示一篇文章,一遍又一遍
【发布时间】:2021-11-30 20:33:18
【问题描述】:

    
  /* 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'];


                  
            

输出是从我的数据库的第一行读取数据的 40 张卡片。谁能帮忙? 我正在使用 xampp。 这段代码是为了显示循环,但如果有人想要完整的代码是here

【问题讨论】:

  • 您将所有 ID 存储在数组 $idarray 中,然后您只需再次运行 40 次相同的查询并始终提取相同的第一行。
  • @AllanSharad 下面的答案对您有帮助吗?如果是这样,请记住将其标记为已接受和/或投票。如果没有帮助,请解释原因。谢谢。

标签: php mysql sql for-loop


【解决方案1】:

您将所有 ID 存储在数组 $idarray 中,但是您并没有真正正确地使用它们。您循环遍历它们,但您只需再运行 SELECT * FROM requests` 40 次,并且始终提取相同的第一行。您永远不会使用 ID 来更改查询。

但是无论如何运行大量单独的查询确实没有意义。如果您只想要前 40 行,请使用 MySQL 的 LIMIT 关键字。它通常在与ORDER BY 结合使用时效果最好。像这样的:

$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;
}

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

【讨论】:

    最近更新 更多