mysqli_fetch_assoc($ result)不显示所有结果

时间:2020-07-18 03:55:10

标签: php html mysql mysqli

我正在尝试使用下面的php代码访问我的查询表。目前,我的mysql数据库中有两个条目。我正在尝试使用 mysqli_fetch_assoc 将表中的所有条目打印到我的网页中,但是我尝试的所有方法是打印第二个条目而不是第一个条目。当我使用while循环 while($ row = mysqli_fetch_assoc($ result ))时,它将打印第二个条目而不是两个条目。如果我使用 print_r($ posts);它会打印第一个条目,而不打印第二个条目。我是php的新手,正试图学习如何将数据库中的所有条目打印到php页面上,但我不了解自己在做什么错。太好了!谢谢!

$sql = 'SELECT * FROM myTable ORDER BY created_at';
$result = mysqli_query($conn, $sql);
$posts = mysqli_fetch_assoc($result);
while($row = mysqli_fetch_assoc($result)){
    print_r($row); 
}
//if I do this I see the first entry title only
echo 'testing title: '. $posts['title'];

mysqli_free_result($result);
mysqli_close($conn);

输出:

Array ( [id] => 2 [title] => SecondTitle [content] => Lorem ipsum dolor sit amet, consectetur 
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. [created_at] => 
2020-07-17 12:32:04 ) testing title: First Title

print_r($ posts)的输出:

Array ( [id] => 1 [title] => First Title [content] => First Content. [created_at] => 2020-07-17 
12:31:42 )

在标签中:

<div class="row">
    <?php foreach ($posts as $post): ?>
        <div>
            <h1><?php echo $post['title'] ?></h1>
            <h3><?php echo $post['created_at'] ?></h3>
            <p> <?php echo $post['content'] ?></p>
        </div>
    <?php endforeach; ?>
</div>

div的输出由于某些原因:

1
1
1

F
F
F

F
F
F

2
2
2

不确定这些信息是否有帮助,但是如果我使用mysqli_fetch_all而不是 mysqli_fetch_assoc ,则文件崩溃,不确定是否与数据库有关或与其他有关。 PHP版本7.3.6

$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);

1 个答案:

答案 0 :(得分:1)

每次调用mysqli结果的mysqli_fetch_assoc()时,返回下一个结果行的assoc数组。 例如: 您有名为user的表有3条记录:

id          name

1           Mark
2           Sebastian
3           Smith

选择所有这些记录后:

$result = mysqli_query("SELECT * FROM user");

第一次提取将返回第一条结果行的assoc数组

$posts = mysqli_fetch_assoc($result);
// $posts["id] = 1 -- $posts["id] = "Mark"

$ result的mysqli_fetch_assoc的seconde调用将返回seconde结果行的assoc数组:

$posts = mysqli_fetch_assoc($result);
    // $posts["id] = 2 -- $posts["id] = "Sebastian"

因此,每次调用将返回下一个结果行,直到没有记录为止,该函数将返回null。 document

因此,如果您希望自己的代码正常工作,我建议您从while循环中删除第一个mysqli_fetch_assoc调用:

// delete this line
$posts = mysqli_fetch_assoc($result);
相关问题