我对PHP和MySQL还是很陌生,我只是想不通。我在论坛周围搜索了所有内容,但没有找到我能理解的答案。希望有人可以向我解释我的代码发生了什么。
英雄是我的代码的一部分:
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if ( mysqli_connect_errno() )
{
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if (!isset($_POST['username']) )
{
// Could not get the data that should have been sent.
die ('Please fill both the username field!');
}
if (isset($_POST['username']))
{
$username = mysqli_real_escape_string($con, trim($_POST["username"]));
$password = mysqli_real_escape_string($con, trim($_POST['password']));
echo $password;
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $username. "' and pass = '" . md5($password). "'");
if ($row = mysqli_fetch_assoc($result))
{
//$_SESSION['user_id'] = $row['uid'];
//$_SESSION['user_name'] = $row['user'];
header("Location: home.php");
} else {
$error_message = "Incorrect username or Password!!!";
}
}
我的索引文件:
<form action="authenticate.php" method="post">
<label for="username">
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" name = "login " value="login">
</form>
答案 0 :(得分:1)
如果mysqli_query()查询失败,它将返回false而不是结果。因此会引发此错误。
“warning ,mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given”
如果查询失败,您必须添加额外的检查,以获取错误并查看查询出了什么问题
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $username. "' and pass = '" . md5($password). "'");
if (!$result) {
echo "SQLSTATE error: " . mysqli_sqlstate($con);
echo "<br>";
echo "SQLSTATE error: " . mysqli_error($con);
exit;
}
if ($row = mysqli_fetch_assoc($result))
{
//$_SESSION['user_id'] = $row['uid'];
//$_SESSION['user_name'] = $row['user'];
header("Location: home.php");
} else {
$error_message = "Incorrect username or Password!!!";
}
这样您就可以看到错误。