简体   繁体   中英

PDO-Login with username or email

I'm trying to convert below statement to PDO.But I'm confused with binding values for :username and :email.

<?php
//$login is either username or email
$user = mysql_query("SELECT * FROM users WHERE (username = '$login' OR email = '$login') AND password = '$password'");
?>

PDO version of above statement I tried.Here $login is either username or email.

<?php
//$login is either username or email
$query_usr = $this->db_connection->prepare("SELECT * FROM members WHERE  username=:username OR email=:user_email) AND password = ':password'");
$query_usr->bindValue(':username', $login, PDO::PARAM_STR);
$query_usr->bindValue(':user_email', $login, PDO::PARAM_STR);
$query_usr->bindValue(':password', $password, PDO::PARAM_STR);
$query_usr->execute();
$query_usr_result_row = $query_usr->fetchObject();
?>

Does this make any sense?

What you've got should work, but as a minor optimization:

SELECT ... WHERE :login IN (username, email) AND password=:password

$query_usr->bindValue(':login', $login, PDO::PARAM_STR);
$query_usr->bindValue(':password', $password, PDO::PARAM_STR);

would work as well. Since you're doing a simple OR comparison of the same value against two fields, the above construct allows you to use a single placeholder and compare it against the relevant fields all at once. Rather than having to bind the same value twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM