Search code examples
phppdo

Fatal error: Uncaught Error: Call to a member function prepare() on null [C:\xampp\htdocs\twitter\core\classes\user.php on line 19]


On logging in, This error pops up.

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\twitter\core\classes\user.php:19 Stack trace: #0 C:\xampp\htdocs\twitter\includes\login.php(17): User->login('user@email.com', 'passwordofuser') #1 C:\xampp\htdocs\twitter\index.php(59): include('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\twitter\core\classes\user.php on line 19

I'm a beginner in PHP and was trying to validate the "entered" email and password by connecting it to SQL DATABASE. I wanted to display an "error" message if the email or password is not available in database. This is user.php.
The error is at line 19.

 $stmt = $this->pdo->prepare("SELECT `user_id` FROM `users` WHERE `email` = :email AND `password` = :password");

user.php

    <?php
class User
{
    protected $pdo;
    
    function _construct($pdo)
    {
        $this->pdo = $pdo;
    }
    public function checkInput($var)
    {
        $var = htmlspecialchars($var);
        $var = trim($var);
        $var = stripcslashes($var);
        return $var;
    }
    public function login($email, $password)
    {
        $stmt = $this->pdo->prepare("SELECT `user_id` FROM `users` WHERE `email` = :email AND `password` = :password");
        $stmt->bindParam(":email", $email, PDO::PARAM_STR);
        $stmt->bindParam(":password",md5($password), PDO::PARAM_STR);
        $stmt->execute();
        
        $user = $stmt->fetch(PDO::FETCH_OBJ);
        $count = $stmt->rowCount();
        
        if($count > 0)
        {
            $_SESSION['user_id'] = $user->user_id;
            header('Location: home.php');
        }
        else
        {
            return false;
        }
    }
}
?>

Now, here is my connection.php

<?php
    $dsn  = 'mysql:host=localhost; dbname=tweety';
    $user = 'root';
    $pass = '';
    
    try
    {
        $pdo = new PDO($dsn, $user, $pass);
    }
    catch(PDOException $e)
    {
        echo 'Connnection error! ' . $e->getMessage();
    }
?>

Here is login.phpenter image description here

I know that this question is asked previously but i can't help myself find a solution.Any help would be appreciated.
WHAT I TRIED:

  1. Tried checking for typo error in connection.php
  2. Tried restarting my SQL server from XAMPP.
  3. Tried referring other "stackoverflow" questions.

Solution

  • In user.php Rename _construct to __construct. Now the constructor isn't executed, so the pdo variable will remain empty.