0

我正在尝试为基于 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/');
}


?>
4

1 回答 1

0

你的代码似乎没问题

当您输入新记录时,请确保您没有输入纯密码字符串,您应该输入密码的 md5 哈希值,因为您的代码查找的是哈希值而不是原始字符串。

于 2013-08-14T04:47:34.360 回答