php - 使用 fetch_assoc 通过 PHP 遍历 MYSQL 结果

标签 php mysql fetch

我正在尝试使用“fetch_assoc”功能来收集表中所有行的所有“博客”字段。

目前,它有点工作;它在 first 行中收集 first“blog”字段的内容,但是对于每隔一行,它从第一行收集相同的数据。

例如,这是我正在使用的代码:

$connection = new mysqli($host,$user,$pass,$db);

$result = $connection->query("SELECT * FROM `Blogs`");
$blogs = array();
$max = sizeof($blogs);
while( $row = $result->fetch_assoc() ) {
    $blogs[] = $row['Blog_Contents'];
    for ($x = 0; $x <= $max; $x++) {
      echo ("<div align=center> <div class=container> <div class='well well-lg wow bounceIn' data-wow-delay='.1s'>" . $blogs[$x] . "</div> </div> </div>");
    } 
}

截至目前,表格中有四行 - 因此 one 行将具有:

Hello this is blog number 1 of the test scheme

行将有:

Hello this is blog number 2 of the test scheme

对于 3 和 4 也是如此,博客中的数量随着其索引的增加而增加。

目前,我的代码产生了以下结果:

Hello this is blog number 1 of the test scheme
Hello this is blog number 1 of the test scheme
Hello this is blog number 1 of the test scheme
Hello this is blog number 1 of the test scheme

谁能告诉我为什么我的代码没有读取其他 Blog_Contents?

也许可以告诉我如何纠正代码?

对不起,如果我没有很好地解释它;我已尽我所能对此进行研究,但找不到我需要的东西。 提前致谢,

Sparkhead95

最佳答案

在 while 循环中初始化 $max 的值

$result = $connection->query("SELECT * FROM `Blogs`");
$blogs = array();

while( $row = $result->fetch_assoc() ) {
    $blogs[] = $row['Blog_Contents'];
    $max = sizeof($blogs);
    for ($x = 0; $x <= $max; $x++) {
      echo ("<div align=center> <div class=container> <div class='well well-lg wow bounceIn' data-wow-delay='.1s'>" . $blogs[$x] . "</div> </div> </div>");
    } 
}

关于php - 使用 fetch_assoc 通过 PHP 遍历 MYSQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31311235/

相关文章:

java - 有什么办法可以使用 jSTL 创建 connectTodb() 函数吗?

php - 查找一行三列中的用户ID

php - 在 php 中放置一些条件后,某些项目不会回显

php - htaccess 搜索查询重定向/重写

mysql - 如何使用 mysql Recipe ?

mysql - SQL 按日期分组冲突

javascript - 在 Parse.com 中使用指针检索数据

javascript - 使用 fetch 检查图像是否存在(函数不返回响应)

javascript - res.render() 和 res.redirect() 的行为类似于 res.send()

php - 在单个属性中插入多个值