【问题标题】:mysqli_fetch_assoc($result) not show all of the results [duplicate]mysqli_fetch_assoc($result)不显示所有结果[重复]
【发布时间】: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);

【问题讨论】:

标签: php html mysql mysqli


【解决方案1】:

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

id          name

1           Mark
2           Sebastian
3           Smith

选择所有这些记录后:

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

第一次获取将返回第一个结果行的关联数组

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

【讨论】:

  • 感谢您的澄清完全丢失了我做错了什么!
猜你喜欢
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 2012-04-08
  • 2019-12-05
  • 2017-02-10
  • 2013-03-21
  • 2017-01-19
  • 2020-10-18
相关资源
最近更新 更多