我在下面的代码中卡住了几个小时。我不知道如何修复这个错误。
Notice: Undefined variable: mysqli in D:\xampp\htdocs\recon\register.php on line 19
Fatal error: Uncaught Error: Call to a member function query() on null in D:\xampp\htdocs\recon\register.php:19 Stack trace: #0 {main} thrown in D:\xampp\htdocs\recon\register.php on line 19
<?php
$conn = new mysqli('localhost', 'root', '', 'user');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$uname = $_POST['uname'];
$psw = $_POST['psw'];
$options = [
'cost' => 12,];
$hashedpassword= password_hash($psw, PASSWORD_BCRYPT, $options);
$result = $mysqli->query("SELECT username FROM registration WHERE username = '$uname'");
$row_count = $result->num_rows;
if($row_count == 1) {
echo 'User already exists, try another one.'; }
else {
$query = "INSERT INTO user (username, password) VALUES(?, ?)";
$statement = $mysqli->prepare($query);
$statement->bind_param('ss', $uname, $hashedpassword);
if($statement->execute())
{
print 'Success! Last inserted record : ' .$statement->insert_id .'<br />';
}
else
{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$statement->close();
}
?>
最佳答案
您正在声明名为 $conn
的 mysqli
实例。这代表您与数据库的连接。您应该在变量 $conn
上调用方法,而不是在(未定义)变量 $mysqli
上调用方法。所以即。你的第 19 行应该是:
$result = $conn->query("SELECT username FROM registration WHERE username = '$uname'")
此外,为了防止查询/网页上的 SQL 注入(inject),您应该使用 prepared statements任何地方(包括SELECT
)。
关于php - Uncaught Error : Call to a member function query() on null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46477835/