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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧