Search code examples
phppdobindvalue

Fatal error: Call to a member function bindValue() on a non-object in


I got the error showing above. I have looked on this website, but I can't find the right fix to solve my problem.

I am trying to write a User-class. The following code is my code so far.

class User
{

    private $_id;

    public function __construct($id)
    {
        $this->_id = $id;
    }

    public function getUsername()
    {
        global $db;

        $query = $db->prepare("SELECT * FROM users WHERE id = ?");
        $query->bindValue(1, $this->_id);

        $query->execute();

    }

}

The result is the following error and I don't know how to fix this...

Fatal error: Call to a member function bindValue() on a non-object in

Edit:

Here is how I am using it:

$user = new User($_SESSION['logged_in']); 
$username = $user->getUsername();

Sidenote: session_start(); is loaded.


Solution

  • Using global variable is really a poor approach.

    Read this blog entry:

    Global Variables Are Bad

    It explains why it is not a good idea.

    If the $db is null, most likely prepare will not return the statement object.

    Then $query will not be a statemnt, therefore bindValue wont be recognize.

    Instead pass the connection to your class, and just stop using globals.

    And also your function was not returning any data, I modify it to return the username.

    class User
    {
    
        private $_id;
        private $db;
    
        public function __construct($id, $conn)
        {
            $this->_id = $id;
            $this->$db = $conn;
        }
    
        public function getUsername()
        {
            $query = $this->db->prepare("SELECT username FROM users WHERE id = ?");
            $query->bindValue(1, $this->_id);
    
            $query->execute();
            $data = $query->fetch();
    
            return $data['username'];
    
        }
    
    }
    

    Usage:

    session_start();
    $id = $_SESSION['logged_in'];
    $conn = new PDO('xxx');
    $user = new User($id, $conn); 
    $username = $user->getUsername();