我正在做一个测试项目,试图了解更多关于 PHP 和 Mysql 的知识。因此,我决定为我的测试网站构建一个身份验证引擎,但我遇到了查询问题。
基本上,如果我运行...
SELECT * FROM users WHERE name="tester" and passwd=md5('pass');
从 mysql 控制台,我得到...
+--------+---------------+----------------------------------+
| name | email | passwd |
+--------+---------------+----------------------------------+
| tester | test@test.com | 1a1dc91c907325c69271ddf0c944bc72 |
+--------+---------------+----------------------------------+
1 row in set (0.00 sec)
但是,当我从我的 PHP 代码(见下文)发出相同的查询(至少我认为它是相同的)时,我似乎得到了 NULL 结果,因此身份验证失败。
<?php
include 'db_connect.php';
$username = $_POST['username'];
$passwd = $_POST['passwd'];
// To protect MySQL injection (more detail about MySQL injection)
//$username = stripslashes($username);
//$passwd = stripslashes($passwd);
//$username = mysql_real_escape_string($username);
//$passwd = mysql_real_escape_string($passwd);
//Encrypted password
$secpasswd = md5($passwd);
$sql="SELECT * FROM users WHERE name='$username' and passwd = $secpasswd";
$result=mysql_query($dbconnect,$sql);
var_dump($result);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
//var_dump($count);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("username");
session_register("passwd");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
最佳答案
你的代码有很多问题。
- 你的SQL查询格式错误
- 您实际上并没有从查询结果中获取任何值
- 你的哈希算法很弱
- 你没有使用准备好的语句
- 您使用的是过时的 session 函数
这是必须的
<?php
include 'db_connect.php';
//Encrypted password
$secpasswd = sha512($_POST['passwd'].$_POST['username']);
$sql = "SELECT * FROM users WHERE name = ? and passwd = ?";
$stm = $pdo->prepare($sql);
$stm->execute(array($_POST['username'], $secpasswd));
$row = $stm->fetch();
if($row){
$_SESSION["username"] = $row[username];
header("location:login_success.php");
exit;
} else {
echo "Wrong Username or Password";
}
请注意此代码使用 PDO用于数据库交互
关于PHP/Mysql 身份验证脚本从查询中获取 NULL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17975279/