Search code examples
phpmysqliwhile-loopmultiple-columns

mysqli_fetch_array while loop columns


Should be pretty basic, but I can't get it to work. I have this code to iterate over a mysqli query:

while($row = mysqli_fetch_array($result)) {
    $posts[] = $row['post_id'].$row['post_title'].$row['content'];
}

It works and returns:

Variable #1: (Array, 3 elements) ↵ 0 (String): "4testtest" (9 characters) 1 (String): "1Hello world!Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!" (99 characters) 2 (String): "2Sample PageThis is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes)." (161 characters)

The problem is that it puts all three colums into one column, so I can't access them seperatly.

This for example:

0 (String): "4testtest" (9 characters)

Should be seperated into 4, test, test

When I do this:

while($row = mysqli_fetch_array($result)) {             
    $posts['post_id'] = $row['post_id'];
    $posts['post_title'] = $row['post_title'];
    $posts['type'] = $row['type'];
    $posts['author'] = $row['author'];  
}   

It only outputs 1 row instead of all three …

Any help is greatly appreciated!


Solution

  • Get all the values from MySQL:

        $post = array();
        while($row = mysqli_fetch_array($result))
        {
            $posts[] = $row;
        }
    

    Then, to get each value:

    <?php 
         foreach ($posts as $row) 
            { 
                foreach ($row as $element)
                {
                    echo $element."<br>";
                }
            }
    ?>
    

    To echo the values. Or get each element from the $post variable