badsyntax badsyntax - 2 months ago 11
MySQL Question

php Call to a member function query() on null

Hello Im getting this error

Call to a member function query() on null


Fatal error: Call to a member function query() on null

Call to member function query() on Null

But neither seems to solve my problem

I have db class

class DB
{
private $link;

public function __construct()
{
$this->link = new mysqli(HOSTNAME, USERNAME, PASSWORD, DBNAME);
if ($this->link->connect_error)
{
exit('Some of the database login credentials seem to be wrong.' . $this->link->connect_error);
}
}
}


Then I attempt to query the database with this class

class UserModel extends DB
{
private $db;

public function __construct()
{
$this->getUser();
}

public function getUser()
{
$query = $this->db->query("SELECT * FROM users");
var_dump($query);
}
}


These files are in site/app/model/file.php

I instantiate db in my site/index.php

Answer

You have a couple of errors here:

  1. As you define own construct in UserModel class, parent __construct, where $link var is defined, is not run. You can add parent::__construct(); to child constructor.

  2. In your parent class you have $link variable, not $db. And $link is private, so it's not avaialble in child classes.

Fixed code is

class DB
{
    protected $link;   // protected here

    public function __construct() 
    {
        $this->link = new mysqli(HOSTNAME, USERNAME, PASSWORD, DBNAME);
        if ($this->link->connect_error) 
        {
            exit('Some of the database login credentials seem to be wrong.' . $this->link->connect_error);
        }
    }
}


class UserModel extends DB
{

    public function __construct()
    {
        // call parent construct and define $this->link
        parent::__construct();  
        $this->getUser();
    }

    public function getUser()
    {
        // use $this->link
        $query = $this->link->query("SELECT * FROM users");
        var_dump($query);
    }
}