简体   繁体   中英

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.

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();

It seams to me that your query object is $db not $query ... if so, then it's normal that the $query is missing bindValue() , because it's not an object, therefor it does not have any methods.

try to use $db->bindValue() and let us know how it went :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM