Search code examples
phpmysqlpdorowecho

Cannot Echo Out String If No Records Returned From PDO Fetch() Request


I have a PDO statement that fetches records form a MySQL database and I want to echo out some text to the page if no records are returned (i.e. a user has yet to add any posts).

I thought after the while loop I could just do an if statement to confirm the presence of the rows. This does indeed echo out the string, but it also echoes out the string when posts are displayed?

<?php

    isset($_GET['username']) ? $username = $_GET['username'] : header("Location: login.php");

    $stmt = $connection->prepare("SELECT * FROM posts WHERE username = :username");
    $stmt->execute([':username' => $username]);                        

    while ($row = $stmt->fetch()) {

        $db_post_id = htmlspecialchars($row['image_id']);
        $db_title = htmlspecialchars($row['image_title']);
        $db_tags = htmlspecialchars($row['image_tags']);
        $db_processed= htmlspecialchars($row['user_processed']);
        $db_username = htmlspecialchars($row['username']);
        $db_profile_image_filename = htmlspecialchars($row['profile_image']);

        if ($db_processed === 'yes') {

?>

<article>
    <!-- HTML goes here that includes above data from database -->
</article>

<?php }

}

if ($row == 0) {
    echo "no data to show";
}

?>

Solution

  • You wish to know if there were results ($stmt->fetch()) or not. If not, print a certain message.

    The following line is a loop that runs while the condition returns true, eventually this condition will return false (all the results have been fetched) and $row would be false. But even if there were no results, fetch() would return false.

    while ($row = $stmt->fetch()) {
    

    So checking the value of $row isn't a good indicator for your request. A solution to your problem would be to use another boolean variable.

        $hasResults = false;
        while ($row = $stmt->fetch()) {
            $hasResults = true;
    

    And then, later on:

    if (!$hasResults) {
        echo "no data to show";
    }