无法在PHP站点中检索MySQL数据
我有这段代码,登录页面将调用它来运行这个php脚本。 但是,代码一直告诉我用户名和密码不正确。 因此,我添加了echo,以查看它从DB中获得的值。 查询很明显返回了用户名和密码的“” 我在数据库中只有一条名为“appthub_DB”的记录,表名为“tbl_user”,表列为“username”和“password” 我想我没有连接错误。我不知道怎么了无法在PHP站点中检索MySQL数据,php,mysql,Php,Mysql,我有这段代码,登录页面将调用它来运行这个php脚本。 但是,代码一直告诉我用户名和密码不正确。 因此,我添加了echo,以查看它从DB中获得的值。 查询很明显返回了用户名和密码的“” 我在数据库中只有一条名为“appthub_DB”的记录,表名为“tbl_user”,表列为“username”和“password” 我想我没有连接错误。我不知道怎么了 <!DOCTYPE HTML> <html> <body> <?php include_once("D
<!DOCTYPE HTML>
<html>
<body>
<?php
include_once("DBConnection.php");
session_start(); //always start a session in the beginning
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST['username']) || empty($_POST['password'])) //Validating inputs using PHP code
{
echo
"Incorrect username or password"; //
header("location: LoginForm.php");//You will be sent to Login.php for re-login
}
$inUsername = $_POST["username"]; // as the method type in the form is "post" we are using $_POST otherwise it would be $_GET[]
$inPassword = $_POST["password"];
echo $inUsername;
echo nl2br ("\n ");
echo $inPassword;
echo nl2br ("\n ");
$stmt= $db->prepare("SELECT username, password FROM tbl_user WHERE username = ?"); //Fetching all the records with input credentials
$stmt->bind_param("s", $inUsername); //bind_param() - Binds variables to a prepared statement as parameters. "s" indicates the type of the parameter.
$stmt->execute();
$stmt->bind_result($UsernameDB, $PasswordDB); // Binding i.e. mapping database results to new variables
//Compare if the database has username and password entered by the user. Password has to be decrypted while comparing.
echo "DBUsername:" ;
echo $UsernameDB ;
echo nl2br ("\n ");
echo "DBPassword:" ;
echo $PasswordDB;
if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))
{
$_SESSION['username']=$inUsername; //Storing the username value in session variable so that it can be retrieved on other pages
header("location: UserProfile.php"); // user will be taken to profile page
}
else
{
echo "Incorrect username or password";
?><br>
<a href="LoginForm.php">Login</a>
<?php
}
}
?>
</body>
</html>
在单独的if语句中运行$stmt->fetch()
语句,首先检查数据库中是否有行,然后从数据库中检索哈希。通过这种方式,您可以调查问题是没有返回行,还是password\u verify()
返回false。因为现在您不知道if
语句中的哪个条件返回false
。您在调用fetch()
之前回显变量,所以它们还不会被设置。@Barmar ok,当我将回显放在fetch()之后查看值时,值是相同的。但是如果($stmt->fetch()&&password\u-verify($inPassword,$PasswordDB))失败了,你在数据库中存储密码时调用了password\u-hash()
了吗?哦,我意识到password\u-verify需要一个$hash,这就是它失败的原因…我将把密码\u-hash键添加到我的代码中