我正在尝试为基于Web的MIS编写登录身份验证。下面是我使用的代码。但是,当给定用户名“admin”和密码“12345”时,即使该记录放在数据表中,也不会登录。
这是表格的SQL代码:
CREATE TABLE accounts (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password CHAR(32) NOT NULL,
last_login DATETIME NOT NULL
);
当我把echo $stmt->num_rows;
0返回时,我想这意味着它在数据库中找不到匹配项。任何人都可以帮助我吗?
<?php
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
// Connect to the MySQL server
$db = new mysqli("localhost", "root", "qwerty", "MIS");
// Determine whether an account exists matching this username and password
$stmt = $db->prepare("SELECT id FROM accounts WHERE username = ? and password = md5(?)");
// Bind the input parameters to the prepared statement
$stmt->bind_param('ss', $username, $password);
// Execute the query
$stmt->execute();
// Store the result so we can determine how many rows have been returned
$stmt->store_result();
if ($stmt->num_rows == 1) {
// Bind the returned user ID to the $id variable
$stmt->bind_result($id);
$stmt->fetch();
// Update the account's last_login column
$stmt = $db->prepare("UPDATE accounts SET last_login = NOW() WHERE id = ?");
$stmt->bind_param('d', $id);
$stmt->execute();
session_start();
$_SESSION['username'] = $username;
// Redirect the user to the home page
header('Location: http://localhost/');
}
?>
答案 0 :(得分:0)
您的代码似乎没问题
当您输入新记录时,请确保您没有输入普通密码字符串,您应该输入密码的md5哈希值,因为您的代码会查找哈希值,而不是 原始字符串。