Search code examples
phpmysqlibindparam

Call to a member function bind_param() on a non-object


The bind parameter function, bind_param() is considered a non object and keeps throwing errors that hurt my head as i'm new to the PHP thing. The code used to connect to the database was originally throwing errors, even though I copied it from my login script where it was working...

<?php
class User {
    private $result;
    private static $db;

    public function __construct($cookie) {
        self::$db = mysqli_connect('localhost', 'username', '', 'dbname');
        var_dump(self::$db);
        
        $query = self::$db->prepare('SELECT * FROM users WHERE cookie=?');
        var_dump($query);
        $query->bind_param('s', $cookie);
        

        $this->result = $query->get_result()->fetch_array();
    }
    
    public static function checkUser($cookie) {
        self::$db = mysqli_connect('localhost', 'username', "", 'dbname');
        
        $query = self::$db->prepare('SELECT cookie FROM users WHERE cookie=?');
        $query->bind_param('s', $cookie);

        $result = $query->get_result()->fetch_array();
        
        if ($cookie == $result[0]) return true;

        return false;
    }

    public function getName() {
        return $this->result['name'];
    }

    public function getSurname() {
        return $this->result['surname'];
    }

    public function getEmail() {
        return $this->result['email'];
    }

    public function getGroup() {
        return $this->result['perm_group'];
    }

    public function getEstablishment() {
        return $this->result['establishment'];
    }
}
?>

The idea was to to make a class (User) so that we can call functions from other pages to get details of the users, such as Cookie. I've been doing this for hours and I honestly don't know whats going on.


Solution

  • mysqli::prepare returns false, if an error occurred.

    $query = self::$db->prepare('SELECT cookie FROM users WHERE cookie=?');
    $query->bind_param('s', $cookie);
    

    If there is an error, you have no result-object to call bind_param on.