0

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"

Jonas
  • 121,568
  • 97
  • 310
  • 388
  • So if your query fails, then `false` gets returned. What would happen, then, if you try to access a boolean's content property? – Chris Forrence Jun 16 '16 at 18:49
  • I want a solution within the function getRow – Göksel Tığlı Jun 16 '16 at 19:04
  • The cleanest solution would be to define a separate function that takes in the object, a string with the desired property, and a default value if the property does not exist. From within that method, you'd check if the passed-in object is indeed an object and not null (if not, return the default value). If the object is an object but the property doesn't exist, return the default value. Otherwise, return the object's property – Chris Forrence Jun 16 '16 at 19:11
  • You don't want to necessarily overload your `getRow` method; it makes it less re-usable throughout your code, and in your case, you'd have to fetch the same row over and over again to get each property. – Chris Forrence Jun 16 '16 at 19:13

2 Answers2

1

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;
    }
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
1

Just check, if you got a result:

if ($page) {
    echo $page->content;
}
Gino Pane
  • 4,740
  • 5
  • 31
  • 46