0

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

Community
  • 1
  • 1
badsyntax
  • 311
  • 4
  • 14

2 Answers2

5

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

Transform

private $link

To

protected $link

This allows the child class to have access to such variable.

And of course, make use of the $this->link instead of the $this->db

Valkyrurr
  • 119
  • 1
  • 12