Notice: Trying to get property 'num_rows' of non-object in

im trying to learn oop php while trying to create crud with oop php im getting following:

Notice: Trying to get property ‘num_rows’ of non-object in

Code are as follows:

class database{
    private $host;
    private $dbusername;
    private $dbpassword;
    private $dbname;

    public $con;

    protected function connect(){
        $this->host       = 'localhost';
        $this->dbusername = 'root';
        $this->dbpassword = '';
        $this->dname      = 'crud';

        $this->con = new mysqli($this->host,$this->dbusername,$this->dbpassword,$this->dbname);
        // return $con;
        if($this->con->connect_error)
        {
            die ("<h1>Database Connection Failed</h1>");
        }
        
        return $this->con;
    }
}

class wwe extends database{
    public function getData(){
        $sql = " SELECT * FROM user";
        $result = $this->connect()->query($sql);
        
        if($result->num_rows > 0){
            $data = array();
            while ($row = $result->fetch_assoc()) {
                   $data[] = $row;
            }
             return $data;
            }else{
             echo "No found records";
            }
    }
}

Table name = user

Immediately before the call to $result->num_rows try adding this line to display what values and functions exist:

echo ‘<pre>’; print_r($result);

As to your posted problem, you made a typo. A good IDE like PhpStorm would have shown you the error.

$this->dname != $this->dbname

If you added the following to the top of the page, it would have pointed you in the right direction
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


Some advice…

  1. Learn PDO instead of Mysqli
    https://phpdelusions.net/pdo

  2. The DB connection parameters should be passed in with Dependency Injection, not hard coded.

  3. Crud operations should be a separate class with the DB connection passed in using Dependency Injection, not extending it.

  4. Learn the SOLID Principles.

Start with my Clean PDO example and you will be off and running like a pro.

1 Like

thank to all who took time to look into my error, it was local server error…