Search code examples
phppdofetchall

PDOstatement not displaying fetched results


Alright so I have created a blog from scratch and mistakenly started to write it with mysql_ statements so I have gone back and rewritten it with PDO statements. I have now encountered a problem with displaying my blog post from my database.

<?php
    include 'includes.php';

    echo '<h3>-----------------------------------------------------</h3>';
    $blogIndex = 'SELECT * FROM blog_post ORDER BY date_posted DESC';
    $blogIndexstmt = $DBH->prepare($blogIndex);
    $blogIndexRows = $blogIndexstmt->fetchAll();

    if(!$blogIndexRows) {
        echo 'No Post Yet.';
    }
        else {
            while($blogIndexRows->nextRowset()) {
                echo '<h2>' . $row['title'] . '</h2>';
                $datePosted = $row['date_posted'];
            echo '<p>' . gmdate('F j, Y, g:i a', $datePosted) . '</p>';
                $body = substr($row['post'], 0, 300);
                echo nl2br($body) . '...<br/>';
                echo '<a href="post_view.php?id=' . $row['id']. '">Read More</a> | ';
                echo '<a href="post_view.php?id=' . $row['id'] . '#comments">' .              
                $row['num_comments'] . ' comments</a>';
                echo '<hr/>';
            }
       }
       $DBH = null;
       echo <<<HTML
       <a href="post_add.php">+ New Post</a>
       HTML;
 ?>

It does not display anything, not even an error code. I was able to do it correctly with the mysql_ statement but I really want to learn how to do this correctly. I am just looking for a nudge in the right direction, you do now have to code it for me. Thanks for you help in advance!


Solution

  • Let's start from the beginning.

    You don't use a prepared statement if you are not passing any parameters.

    What does that mean? Simply issue PDO's query function.

    It would be like this:

    $query = $DBH->query('SELECT * FROM blog_post ORDER BY date_posted DESC');
    

    If something went wrong, $DBH->query will return FALSE or PDOStatement on success. So next line is to check whether it's false:

    if($query === false)
    {
        echo $DBH->errorCode();
    }
    else 
    {
        // Everything went fine, let's fetch results
        $results = $query->fetchAll(PDO::FETCH_ASSOC);
    
        // If there are any records returned, our array won't be empty.
        if(count($results))
        {
            // $results contains all of your records. You can now loop it with for, foreach and you don't need a while loop anymore
            foreach($results as $row)
            {
                print_r($row);
            }
        }
        else
        {
            echo "There are no records in the database table :(";
        }
    }