Göksel Tığlı Göksel Tığlı - 5 months ago 24
PHP Question

Php Trying to get property of non-object in PDO null value

I'm using MySQL PDO class. I want to get a row. it successfully completes this code. But if there is no data. I get 'Notice: Trying to get property of non-object in PDO'

<?php
...

public static function getRow($query, $bindings = null)
{
if(!$stmt = self::query($query, $bindings))
return false;

$result = $stmt->fetch();
return $result;
}

$page = DB::getRow('SELECT * FROM page WHERE id = "homepage" ');
echo $page->content;

?>


if available id data "homepage".
output:

"Homepage bla bla...";

if there is no data.
output:

"Notice: Trying to get property of non-object in /var/www/vhosts/kkkk.com/httpdocs/index.php on line 139"

How do I fix it ?

"I want a solution within the function"

Answer

When there's no data $stmt->fetch fetches something that is not object. And this something definitely has no content property.

Use a simple check, whether you have object or not:

echo $page? $page->content : 'No content available';
// or more complicated if you don't want to output anything when there's no data:
if ($page) {
    echo $page->content;
}

Update:

public static function getRow($query, $bindings = null, $property_name = '')
{
    if(!$stmt = self::query($query, $bindings))
        return false;

    $result =  $stmt->fetch();
    if ($result) {
        return $property_name? $result->$property_name : $result;
    } else {
        return false;
    }
}
Comments