You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP PDO出现Call to a member function prepare() on null致命错误求助

Fixing the "Call to a member function prepare() on null" PDO Error

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.php is 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 CRUD class 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:09:59