dswqw66280 2014-07-09 15:58
浏览 38

PDO登录系统无法正常工作

I know I'll get a bunch of down-votes, but I am new to PDO and need to make a login system for a little web application. I can't seem to get it right:

<?php

include 'Config.php';

$username      = strtolower($_POST['username']);
$password      = md5($_POST['password']);
$hidden        = $_POST['hidden'];
$submit        = $_POST['submit'];
$host          = $config['mysql']['host'];
$mysql_user    = $config['mysql']['user'];
$mysql_pass    = $config['mysql']['pass'];
$db            = $config['mysql']['db'];

if(isset($username) && isset($password) && isset($submit) && !isset($hidden)) {

    try {
        $opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
        $objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
        $objQuery    = $objDatabase->prepare("SELECT * FROM users WHERE username=:username");
        $objQuery->bindValue(':username', $username);
        $objQuery->execute();
        $row         = $objQuery->fetch(PDO::FETCH_ASSOC);
        if(!empty($row)) {
            if($username == $row['username'] && $password == $row['password']) {
                $_SESSION['logged_in'] = true;
                $_SESSION['username']  = $row['username'];
                header('Location: i/');
            } else
                header('Location: index.php?err=true&type=1');
        } else
            header('Location: index.php?err=true&type=2');
    } catch(PDOException $e) {
        die($e->getMessage());
    }

}

?>

I always get error 2 - account not found. I'm logging in with user "test" and password "test". In the database is an account with username "test" and the password is an MD5 hash of "test".

  • 写回答

1条回答 默认 最新

  • doukao2180 2014-07-09 15:59
    关注

    Your sql statement is wrong:

    SELECT * FROM users WHERE username=':username'
    

    You should not put your placeholder in quotes as now it is taken literally by mysql.

    It should be:

    SELECT * FROM users WHERE username=:username
    

    You should also tell PDO to throw exceptions:

    $opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
    $objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
    

    So that it will tell you when something goes wrong.

    Edit: As noted by @LozCheroneツ you also need to execute the query before you can fetch a row:

    $objQuery->bindValue(':username', $username);
    $objQuery->execute();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题