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

使用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条)

报告相同问题?