Search code examples
phpmysqlpdobindvalue

PHP: PDO bindValue() causes 0 results to be returned


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;
        }

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";