Fatal error: Uncaught Error: Call to a member function prepare() on null

前端 未结 1 416
傲寒
傲寒 2020-12-22 03:19

These are three files

config.php
functions.php
index.php

I got an error \"Fatal error: Uncaught Error: Call to a member function prepare()

相关标签:
1条回答
  • 2020-12-22 03:46

    You will not get the $pdo variable in DatabaseConnection class from global scope. So, your $pdo variable is basically null. You can change you code as below:

    config.php:

    class DatabaseConnection {
       public function __construct() {
          try {
             return new PDO('mysqli:host=xxx;dbname=xxx', 'root', '');            
          } catch(PDOException $e) {
              exit('Database error');
          }
       }
    }
    

    Then:

    class LoginRegistration {
        private $database
    
        function __construct() {
            $this->database = new DatabaseConnection();
        }
    
        public function registerUser($username, $password, $name, $email, $website) {
    
          $query = $this->database->prepare("SELECT id FROM users WHERE username = ? AND email = ?");
          $query->execute(array($username, $email));
          $num = $query->rowCount();
    
          ...
    

    However, I would rather extend the DatabaseConnection class rather instantiating it within the LoginRegistration class. That is:

    config.php:

    class DatabaseConnection {
       protected $pdo;
       public function __construct() {
          try {
             $this->pdo = new PDO('mysqli:host=xxx;dbname=xxx', 'root', '');            
          } catch(PDOException $e) {
              exit('Database error');
          }
       }
    }
    

    Then extend DatabaseConnection from LoginRegistration class:

    class LoginRegistration extends DatabaseConnection {
        // constructor is not needed anymore
        public function registerUser($username, $password, $name, $email, $website) {
    
          $query = $this->pdo->prepare("SELECT id FROM users WHERE username = ? AND email = ?");
          $query->execute(array($username, $email));
          $num = $query->rowCount();
    
          ...
    
    0 讨论(0)
提交回复
热议问题