【发布时间】:2020-11-07 21:05:49
【问题描述】:
我正在尝试使用下面的 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);
【问题讨论】:
-
这能回答你的问题吗? mysqli_fetch_assoc not showing all results