Question

I've having some troubles with the PDO bindValue() function. Whenever I seem to use it, my queries always return 0 results. However it works fine if I put $user and $pass straight into the sql without the use of bindValue()

$user is a string
$password is a sha1() hash

public function login($user, $pass) {
            global $CMS;

            $sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` WHERE `username` = ':user' AND `password` = ':pass'";
            $query = $CMS->prepare_query($sql);
            $query->bindValue(':user', $user, PDO::PARAM_STR);
            $query->bindValue(':pass', $pass, PDO::PARAM_STR);
            $query->execute();

            # User successfully authenticated
            if ($query->rowCount() == 1) {
                # Get all data from DB and populate class variables
                self::populate_user_data($user);
                session_register($user . "-" . base64_encode($_SERVER['REMOTE_ADDR']));
                return true;
            }

            # User failed authentication            
            return false;
        }
Was it helpful?

Solution

You should not put the quotes around the values yourself, they will be added (if needed, such as in the case of strings - this case):

$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` 
        WHERE `username` = :user AND `password` = :pass";

OTHER TIPS

The placeholders in a prepared statement must not be quoted; PDO is already doing all the quoting. You want:

 $sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` " .
        "WHERE `username` = :user AND `password` = :pass";

When using prepared statements, the values get escaped automagically.

This means, that you don't have to set quotes around the arguments.

try:

$sql = "SELECT `username,`password` ".
       "FROM `" . TB_PREFIX . "users` ".
       "WHERE `username` = :user AND `password` = :pass";

and you should be fine.

As a side note though: you should NEVER store user passwords literally. Check this excellent article: You're Probably Storing Passwords Incorrectly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top