Search code examples
phpprepare

Fatal error: Call to a member function prepare() on null, Connection is correct


So I'm currently making a login thingie for someone, and when I push the login button, this pops into my screen:

Fatal error: Call to a member function prepare() on null in /Applications/XAMPP/xamppfiles/htdocs/application/classes/users.php on line 37

This is what's happening in that area, of that file:

public static function login() // 32
{ // 33
    $username = $_POST['username']; // 34
    $password = $_POST['password']; // 35
    $query = self::$connection->prepare('SELECT * FROM users WHERE username = :username'); // 36
    $query->execute(array(':username' => $username)); // 37

Nothing weird there. The self::$connection element is from my constructor:

 public function __construct()
 {
     self::$connection = Core\Database::connect();
 }

And yes, I did do Use DeGier\Core;

The database file is pretty basic:

public static function connect()
{
    try
    {
        self::$conn = new \PDO('mysql:hostname=localhost;charset=utf8;dbname=degieradmin;', 'root', ********);
        self::$conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        self::$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }
        catch (\PDOException $e)
    {
        throw new \PDOException('PDO error:' . $e->getMessage());
    }
    return self::$conn;
}

I did all the basic stuff;

  • I checked if MySQL was turned on,
  • I checked if the DB connection details where correct,
  • I checked if that particular DB existed.
  • I checked if the file was readable.

I couldn't find anything wrong.

So how is it that this kind of stuff normally works, but this time it doesn't?


Solution

  • You are setting your static variable, the database connection, in the constructor of your class.

    However, the constructor is only run when an object of that class is created.

    So you should not do that there unless you are absolutely certain that the very first thing you do, is create an instance of your object.

    You should initialize your database somewhere else and / or check in your login method whether it is set.