我正在尝试实现一个登录系统,除了可以返回0的PHP脚本之外,它大部分都可以正常工作:
// $username_err & $password_err is empty, gets reset every time as "".
if(empty($username_err) && empty($password_err)){
$query = "SELECT rowid, username, password FROM admin_login WHERE username = ?";
if($stmt = mysqli_prepare($db, $query)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
// Doesn't work here, works up until here.
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $rowid, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $rowid;
$_SESSION["username"] = $username;
header("location: index.php");
}else{
$password_err = "Invalid password";
}
}
}else{
$username_err = "No such account exists.";
}
}else{
echo "An error occurred.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($db);
这永远都行不通,因为它不满足mysqli_stmt_num_rows == 1的条件而卡住,而是返回0。它确实是通过MySQL直接通过工作台来工作的:
SELECT rowid, username, password FROM admin_login WHERE username = "admin";
返回符合条件的1行。
**编辑:这是我的新代码; **
<?php
require_once "_php/login/config.php";
$username = $password = "";
$err = "";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty(trim($_POST["username"]))) {
$err = "Enter a username";
} else {
$password = trim($_POST["password"]);
}
if (empty(trim($_POST["password"]))) {
$err = "Enter a password";
} else {
$password = trim($_POST["password"]);
}
$stmt = $db->prepare("SELECT rowid, username, password FROM admin_login WHERE username = ?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$stmt->store_result();
$user = $stmt->get_result()->fetch_assoc();
if ($user && password_verify($_POST["password"], $user["password"])) {
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
header("location: index.php");
} else {
$err = "Wrong password";
}
}
//end of program
它抛出:
致命错误:未捕获错误:在目录 /login_script.php:25中的布尔值上调用成员函数fetch_assoc():25堆栈跟踪:#0 目录 / login。 php(2):require()#1 {main}在第25行的目录 /login_script.php中抛出
作为参考,login_script是PHP脚本,login是作为php的前端。
答案 0 :(得分:0)