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
相关产品推荐
相关产品推荐

