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

我正在尝试使用下面的 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);


扬帆大鱼
浏览 242回答 1
1回答

白衣染霜花

每次调用 mysqli_fetch_assoc() 的 mysqli 结果,都会返回下一个结果行的 assoc 数组。例如:您的表名为 user 有 3 条记录:id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Mark2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Sebastian3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Smith选择所有这些记录后:$result = mysqli_query("SELECT * FROM user");第一次获取将返回第一个结果行的关联数组$posts = mysqli_fetch_assoc($result);// $posts["id] = 1 -- $posts["id] = "Mark"$result 的 mysqli_fetch_assoc 的第二次调用将返回第二结果行的 assoc 数组:$posts = mysqli_fetch_assoc($result);&nbsp; &nbsp; // $posts["id] = 2 -- $posts["id] = "Sebastian"所以每次调用,都会返回下一条结果行,直到没有记录,该函数才会返回null。文档因此,如果您希望代码按您希望的方式工作,我建议您删除 while 循环中的第一个 mysqli_fetch_assoc 调用:// delete this line$posts = mysqli_fetch_assoc($result);
打开App,查看更多内容
随时随地看视频慕课网APP