【问题标题】:Using fetch_assoc to iterate through MYSQL results with PHP使用 fetch_assoc 通过 PHP 遍历 MYSQL 结果
【发布时间】:2015-07-09 16:01:16
【问题描述】:

我正在尝试使用“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

【问题讨论】:

  • $blogs = array(); $max = sizeof($blogs); 始终设置 $max=0 ,因此您的 for 循环将始终只有一个交互。你想通过这个结构来达到什么目的?
  • @VolkerK 啊,当然,我没有注意到我这样做了。我试图将 blogs[] 设置为与表中的行数相同
  • for循环不应该在while循环中

标签: php mysql fetch


【解决方案1】:

在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>");
    } 
}

【讨论】:

  • 谢谢你-我想通了。在这里也发布了我的解决方案。
【解决方案2】:

感谢@VolkerK 指出 - 我的代码中有这个:

$blogs = array(); $max = sizeof($blogs);

所以我的 $max 变量总是 0。

我将代码更改为:

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

$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='." . $x . "s'>" . $blogs[$x] . "</div> </div> </div>");
} 

现在它可以工作了。

再次感谢。

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多