php - 使用简单的 PHP 登录用户但数据库查询失败
问题描述
我试图查询我的数据库以返回具有匹配 id 的用户,但似乎查询没有正确查询数据库,因为没有采取任何操作。该页面只是刷新而没有消息,并再次显示登录表单。我也尝试过使用 mysqli_fetch_array() 函数来返回数据库中的匹配行,但它也失败了。
<?php
if (isset ($_POST['username']) && (isset ($_POST['password']))){
$username = $_POST['username'];
$password = $_POST ['password'];
//encrypting the password with md5 hashing
$password_hash = md5($password);
if (!empty ($username) && (!empty($password))) {
$query= "SELECT id FROM users WHERE username = ‘$username'
AND password = '$password_hash' ";
if ($query_run = mysqli_query ($mysql_conn, $query)) {
$query_num_rows = mysqli_num_rows ($query_run);
if ($query_num_rows == 0) { //checks to see if username and password exists in database
echo 'Invalid username or password.';
}
else if ($query_num_rows == 1) {
echo 'OK';
}
}
}
?>
<form action = "<?php echo $current_file; ?>" method = "POST">
Username: <br>
<input type = "textarea" name = "username"><br><br>
Password: <br>
<input type = "Password" name = "password"><br><br>
<input type = "submit" value = "Log in">
</form>
解决方案
我已经测试了以下,它工作正常。请注意,它只是检查用户名,如下所示。
<?php
//connect to the database - $mysql_conn as connection
if (isset ($_POST['username']) && (isset ($_POST['password']))){
$username = $_POST['username'];
$password = $_POST ['password'];
//encrypting the password with md5 hashing
$password_hash = md5($password);
if (!empty ($username) && (!empty($password))) {
$query= "SELECT userID FROM crUsers WHERE userName = '$username';";
//$query= "SELECT id FROM users WHERE username = '$username' AND password = '$password_hash';";
$query= "SELECT id FROM users WHERE username = '$username';"; //Checking just username
$query_run = mysqli_query ($mysql_conn, $query);
$query_num_rows = mysqli_num_rows ($query_run);
if ($query_num_rows == 0) {
echo 'Invalid username or password.';
}
else if ($query_num_rows == 1) {
echo 'OK';
}
else {
echo 'More than one user with these credentials';
}
}
}
?>
<!DOCTYPE html>
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="UTF-8" />
</head>
<body>
<form method = "POST">
Username: <br>
<input type = "text" name = "username"><br><br>
Password: <br>
<input type = "Password" name = "password"><br><br>
<input type = "submit" value = "Log in">
</form>
</body>
</html>
推荐阅读
- javascript - React、Express、socket.io 没有实时更新,控制台没有错误
- sql - 我可以使用 sql 查询来获取 PostgreSQL 数据库中所有主键和外键的列表吗
- javascript - 为什么OR(||)语句在while循环中不起作用,javascript
- java - 有没有办法使用java的LocalDateTime类获取oracle数据库服务器的本地时间和时间?
- c++ - 如果一个引用被声明为指向它自己呢?例如 int& x = x;
- php - 在 PHP 中模拟不存在的接口
- r - 在一行中按字数对字符串向量进行子集
- ruby-on-rails - 如何更改写入 Rails 中 STI 的继承列的类名?
- vue.js - 为什么我在 GitHub 页面上托管的静态 nuxt.js 应用程序上获得资源 404?
- python - 如何禁用我的文件旁边的 VS Code Git 黄色图标?