0

I keep getting an function rowCount() on a non-object error on two different pages. Any idea why this is happening and how I can alter the code to prevent it from happening?

Error - as below

Fatal error: Call to a member function rowCount() on a non-object in /opt/lampp/htdocs/xampp/index.php on line 35

The code:

$sql = "SELECT * from idea ORDER BY datetime DESC LIMIT 50;";
$result = $pdo->query($sql);

if($result->rowCount() > 0 && !empty($result)) // line 35
{
    foreach ($result as $row) 
    {
    $id = $row['id'];
    $title = $row['title'];
    $idea = $row['idea'];

    echo '<span class="idea" id="'.$id.'"><strong style="color: #0081C5">' . $title . "</strong>&nbsp;-&nbsp;" . $idea . '&nbsp;<a class="delete" href="#">[Delete]</a></span>';
    }
}

Error - as below

Fatal error: Call to a member function rowCount() on a non-object in /opt/lampp/htdocs/xampp/assets/update.php on line 6

The code

 $sql = "SELECT * from idea ORDER BY datetime DESC LIMIT 50;";
$result = $pdo->query($sql);

if($result->rowCount() > 0 && !empty($result)) // line 6
    {
        foreach ($result as $row) 
        {
        $id = $row['id'];
        $title = $row['title'];
        $idea = $row['idea'];

        echo '<span class="idea" id="'.$id.'"><strong style="color: #0081C5">' . $title . "</strong>&nbsp;-&nbsp;" . $idea . '&nbsp;<a class="delete" href="#">[Delete]</a></span>';
        }
    }

1 Answer 1

3

change it to this

if(!empty($result) AND $result->rowCount() > 0)

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain why? (For the good of OP and future visitors)
his code first checks if result is not empty and THEN only tries calling rowCount on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.