dqd22496 2011-08-16 11:16
浏览 35

PDO脚本获取行数不起作用?

I'm new to PDO PHP (just started today). I am attempting too write a login function, but it is returning false, even though i know the credentials are correct.

I think is is the attempt to get the amount of rows which is tripping the script up, can you help?

function check_login($email, $username, $password)
{
    $host = 'localhost';
    $port = 3306;
    $database = 'example';
    $username = 'root';
    $password = '';

    $dsn = "mysql:host=$host;port=$port;dbname=$database";
    $db = new PDO($dsn, $username, $password);
    $password = md5($password);

    $statement = $db->prepare("SELECT * FROM users WHERE email = ? or username = ? and password = ?");
    $statement->execute(array($email, $username, $password));

    while ($result = $statement->fetchObject()) {
        $sql = "SELECT count(*) FROM users WHERE email = ? or username = ? and password = ?";
        $result1 = $db->prepare($sql);
        $result1->execute(array($email, $username, $password));
        $number_of_rows = $result1->fetchColumn();
        if ($number_of_rows == 1)
        {

            $_SESSION['login'] = true;
            $_SESSION['uid'] = $result->uid;
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongyuan8469 2011-08-16 12:41
    关注
    1. This:

      WHERE email = ? or username = ? and password = ?
      

      ... equals this:

      WHERE email = ? or (username = ? and password = ?)
      

      ... due to operator precedence. That means that if you validate with an e-mail address, you are not required to provide a valid password to log in.

    2. Once you've found out whether the user exists, you make a second query to count the number of matching users. The database table should not be able to hold duplicate users in the first place! Columns username and email should be defined as unique indexes.

    3. There's no point in using a while loop if it's going to return in the first iteration. It may work, but it's confusing.

    This should be enough:

    $statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
    $statement->execute(array($email, $username, $password));
    
    if ($result = $statement->fetchObject()) {
        $_SESSION['login'] = true;
        $_SESSION['uid'] = $result->uid;
        return TRUE;
    }else{
        return FALSE;
    }
    

    Edit: BTW, you should not be storing passwords in plain text. Countless sites have been hacked and their passwords stolen. Google for salted passwords.

    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法