douliaopan1419 2013-05-22 18:50
浏览 7
已采纳

MySQL查询到PDO

I'm switching from MySQL to PDO and I'm unsure if this query is correct.. would I still be required to write the if command.

public function User_Login($_iUsername,$_iPassword) {
    $username=mysql_real_escape_string($_iUsername);
    $password=mysql_real_escape_string($password);
    $md5_password=md5($_iPassword);
    $query=mysql_query("SELECT _iD FROM users WHERE _iUsername='$_iUsername' and _iPassword='$md5_password' AND _iStatus='1'");
    if( mysql_num_rows( $query ) == 1 ) {
        $row = mysql_fetch_array( $query );
        return $row['_iD'];
    } else {
        return false;
    }
}

TO

public function User_Login($_iUsername,$_iPassword) {
    $md5_password = md5($_iPassword);
    $sth = $db->prepare("SELECT _iD FROM users WHERE _iUsername='$_iUsername' and _iPassword='$md5_password' AND _iStatus='1'");
    $sth->execute();

    $result = $sth->fetchAll();
}
  • 写回答

1条回答 默认 最新

  • doubingjiu3199 2013-05-22 18:54
    关注

    First off, you're not properly parameterizing the query. It's great that you're using PDO, but one of the main purposes of the change is the ability to parameterize queries. Secondly, md5 is a very weak hash. I suggest using bcrypt instead. Finally, PDOStatement::rowCount is the method you are looking for.

    $sth = $db->prepare("SELECT _ID FROM users WHERE _iUsername = ?
        AND _iPassword = ? AND _iStatus = 1");
    $sth->execute(array($_iUsername, $md5_password));
    if ($sth->rowCount() == 1) {
        $row = $sth->fetch(PDO::FETCH_ASSOC);
        return $row['_iD'];
    }
    else {
        return false;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?