正如我的代码现在一样,无论用户名/密码是否匹配,我总是得到echo "Username/Password incorrect.";
。我的问题是,我在下面的代码中做错了什么,因为php始终回显“用户名/密码不正确”
<?php
require 'privstuff/dbinfo.php';
$password1 = $_POST["password1"];
$username = $_POST["username"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner@othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("SELECT username, password FROM accounts WHERE username=? and password=?")) {
$db_pw = password_hash($password1, PASSWORD_BCRYPT);
$stmt->bind_param("ss", $username, $db_pw);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Logged in.";
}else{
echo "Username/Password incorrect.";
}
$stmt->close();
}
$stmt->close();
$mysqli->close();
?>
更新我已将if ($stmt->affected_rows > 0)
更改为if ($stmt->num_rows)
。尽管如此仍然无效
更新2 我意识到问题是我使用password_hash($password1, PASSWORD_BCRYPT);
我没有意识到哈希每次都会给出不同的字符串。我不了解如何使用password_verify
答案 0 :(得分:4)
mysqli_stmt_affected_rows()
的文档说:
此功能仅适用于更新表的查询。要从SELECT查询中获取行数,请改用mysqli_stmt_num_rows()。
您还需要先调用mysqli_stmt_store_results()
,以缓冲结果。
$stmt->store_results();
if ($stmt->num_rows > 0) {
...
}
答案 1 :(得分:0)
我明白了。我不应该再次使用password_hash。我没有意识到使用password_hash给出了不同的结果。然后我将其更改为使用password_verify。
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $username);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
if(password_verify($password1, $result))
{
echo("Hello");
}else{
echo("No-Go");
}
$mysqli->close();
?>