PHP PDO出现Call to a member function prepare() on null致命错误求助
Hey there, let's work through this frustrating fatal error you're hitting. The core issue here is that $this->Db in your CRUD class is null when you try to call prepare() on it. Let's break down the most likely fixes step by step:
1. Fix the Constructor Syntax (The #1 Culprit)
PHP requires constructor methods to have two underscores (__construct), but your code uses only one (_construct). This means the constructor never runs automatically when you instantiate the class, so $this->Db never gets assigned the database connection you pass in.
Here's the corrected CRUD class:
<?php class CRUD { private $Db; // Note the two underscores here! public function __construct($DB_CON) { $this->Db = $DB_CON; } public function getUserByUsername($username) { // Finish the prepare() call with a valid query $sth = $this->Db->prepare("SELECT * FROM users WHERE username = :username"); $sth->bindParam(':username', $username); $sth->execute(); return $sth->fetch(PDO::FETCH_ASSOC); } }
2. Verify Your Database Connection (db_connect.php)
Even with a fixed constructor, you need to ensure db_connect.php returns a valid PDO instance (not null). Double-check your connection code handles errors properly so you can catch any connection failures early:
<?php // Example db_connect.php code try { $dbConnection = new PDO( 'mysql:host=localhost;dbname=your_database_name;charset=utf8mb4', 'your_db_username', 'your_db_password' ); // Enable exceptions to make debugging easier $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("Database connection failed: " . $e->getMessage()); }
Then, when you instantiate the CRUD class, make sure you're passing this valid connection:
require_once 'db_connect.php'; $crud = new CRUD($dbConnection);
3. Quick Additional Checks
- Confirm
db_connect.phpis being included correctly (no typos in the file path, no file permission issues blocking access). - If you're using a framework or autoloader, ensure the
CRUDclass is loaded before you try to use it. - Add a quick debug check in your constructor to validate the connection:
public function __construct($DB_CON) { if (!$DB_CON instanceof PDO) { die("Invalid PDO connection passed to CRUD class"); } $this->Db = $DB_CON; }
内容的提问来源于stack exchange,提问作者ajMad88

