PHP/Mysql 身份验证脚本从查询中获取 NULL 结果

标签 php mysql authentication

我正在做一个测试项目,试图了解更多关于 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/

相关文章:

MySQL错误: Illegal Mix of Collations

php - 是否可以在PHP中将WAV文件转换为AIFF,反之亦然?

mysql - 在 select where 语句中展开查询结果

javascript - 从 js 页面发送数据后,我无法插入

authentication - Swift - Parse.Com - 登录 - 'selector' 未找到

php - 最简单的嵌入式 PHP 身份验证解决方案?

php - 是否有可用的 PHP CQL 驱动程序/客户端

php - 我如何构造这个嵌套的 mysql 查询?

php - 如何创建网站 API

authentication - 如何使用 curl 登录支持 Okta 的站点?