0

I'm building a simple log-in function for a site, and I've come across some trouble. When I try to log in to the site, I keep getting the error that username and password doesn't match. This is of course an error I've defined myself, but the problem is that I shouldn't get it in this case.

I printed the calculated hash for the password, and made sure that this step was properly performed, which it was. After this, I ran

SELECT * FROM members WHERE user='username' AND pass='hashed_password';

directly toward my MySQL database, supplying the username and hash directly. This returned the desired values. My PHP code looks like this:

$dsn = "mysql:host=localhost;dbname=my_db";
$u = "localhost";
$pdo = new PDO($dsn,$u);
$query = $pdo->prepare("SELECT * FROM members WHERE user=':username' AND pass=':hashed_pass'");
$query->execute(array(':username'=>$username,':hashed_pass'=>$hashed_pass));
$result = $query->fetch();
if($result){
    //Log in user
}else{
    //Print error
}

This does not return anything, even though I supply the correct values, it keeps giving me the error. I'm not sure what might cause the problem, but if I'd make a guess I'd say that it has to do with the charsets. My database uses UTF-8. Although, I still got the desired results from MySQL when querying the database directly though SSH with ISO-8859 encoding.. So I'm really not sure. Any help would be much appreciated!

5
  • Where do $username and $hashed_pass come from and are you sure they contain correct values? Use echo to confirm this. Commented Jun 23, 2013 at 18:23
  • This is totally unrelated but You're better off selecting the user with a username then matching the password of the resulting user table with the hashed password with php. Commented Jun 23, 2013 at 18:35
  • @CreativityKills Not sure I agree with this. Commented Jun 23, 2013 at 18:56
  • @PhilipWhitehouse it's safer and makes more sense. Select row with username, compare the password with inputted password using if && === it's more flexible and extendible. Commented Jun 23, 2013 at 20:10
  • 1
    @CreativityKills Could you explain why that would make if safer? Commented Jun 23, 2013 at 20:16

1 Answer 1

2

Try removing quotes. PDO does NOT replace given parameters if they are wrapped in quotationmarks.

Example:

$st = $db->prepare('INSERT INTO users ( name, surname ) VALUES( :name, ":surname" )');
$st->execute( array( ':name' => 'John', ':surname' => 'Carlo' ) );

Results:

-> John, :surname

You can also use debugDumpParams to see the parameters are either correct or not. http://www.php.net/manual/en/pdostatement.debugdumpparams.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.