0

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.

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Lycaon
  • 51
  • 2
  • 9

2 Answers2

2

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();
meda
  • 45,103
  • 14
  • 92
  • 122
-1

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

Ares Draguna
  • 1,641
  • 2
  • 16
  • 32