我的for循环只允许一篇文章一遍又一遍地显示




/* 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。这段代码是指循环,但是如果有人想要完整的代码在这里

您将所有id存储在数组$idarray中,但随后您没有真正正确使用它们。你循环它们,但是你只是运行SELECT * FROM请求’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

最新更新