douxiaochun4964 2015-07-09 07:49
浏览 59
已采纳

使用fetch_assoc通过PHP迭代MYSQL结果

I'm attempting to use the "fetch_assoc" functionality in order to collect all the "blog" fields of all the rows in my table.

At the moment, it sort of works; it collects the contents of the first "blog" field in the first row, however for every other row it collects the same data from the first row.

So, for example, this is the code I'm using:

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

There are four rows in the table as of now- so row one would have:

Hello this is blog number 1 of the test scheme

Row two would have:

Hello this is blog number 2 of the test scheme

And the same for 3 and 4, with the number in the blog increasing with it's index.

At the moment, my code is producing the following result:

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

Could anyone please tell me why my code isn't reading the other Blog_Contents?

And maybe tell me how to rectify the code?

Sorry if I wasn't explaining it very well; I have tried to research this as much as I could but couldn't find what I needed. Thanks in advance,

Sparkhead95

  • 写回答

2条回答 默认 最新

  • doutuanxiao4619 2015-07-09 08:01
    关注

    Thanks to @VolkerK for pointing it out- I had this in my code:

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

    So my $max variable was always 0.

    I changed my code to this:

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

    And now it works.

    Thanks again.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办