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

PHP简易登录应用开发报错:Call to a member function prepare() on null

解决"Call to a member function prepare() on null"致命错误

嘿,我一眼就揪出了你代码里的核心问题,这也是触发这个致命错误的直接原因:

1. 构造函数名写错了!

PHP 中类的构造函数必须是两个下划线的 __construct(),而你写的是 _construct()(只有一个下划线)。这个小失误会导致构造函数根本不会被自动调用,$this->con 也就永远是 null,当你调用 $this->con->prepare() 时自然就会抛出"Call to a member function prepare() on null"的错误。

2. 还有两处小bug需要修正

除了构造函数的问题,你的 addUserInLogin 方法里还有两个容易忽略的问题:

  • bind_param 的第一个参数必须是数据类型标识字符串(比如s代表字符串),你直接传了$uname,这会导致参数绑定失败;
  • else 分支漏写了return语句,会导致方法在执行失败时没有返回值。

修正后的完整代码

<?php
class DbOperation {
    private $con;

    // 修正:构造函数改为双下划线
    function __construct() {
        require_once dirname(__FILE__).'/DbConnect.php';
        echo "Hereee";
        $db = new DbConnect();
        $this->con = $db->connect();
        
        // 可选:在这里加个判断,提前确认连接是否成功
        if (!$this->con) {
            die("数据库连接失败: " . mysqli_connect_error());
        }
    }

    function addUserInLogin($uname, $pass) {
        $pword = md5($pass);
        $stmt = $this->con->prepare("INSERT INTO `login` (`uname`, `pword`) VALUES (?, ?);");
        
        // 修正:bind_param第一个参数是数据类型,两个字符串参数用"ss"
        $stmt->bind_param("ss", $uname, $pword);
        
        if ($stmt->execute()) {
            return true;
        } else {
            // 修正:补上return语句
            return false;
        }
    }
}
?>

额外排查建议

  • 检查 DbConnect.php 里的 connect() 方法,确保它正确返回了 mysqli 连接对象,比如确认数据库主机、用户名、密码、数据库名配置没有拼写错误;
  • 确认你的数据库中确实存在 login 表,且 uname、pword 字段的类型和长度符合插入数据的要求;
  • 另外提个小建议:md5 已经不是安全的密码哈希方式了,建议改用 password_hash() 和 password_verify() 来处理密码,安全性会高很多。

内容的提问来源于stack exchange,提问作者Krishna Preetham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:55:11