0

What wrong with my code? please need some help cause I dont see any problem. but still password_verify doesnt work.

public function login($username, $password){
    global $db;
    $sql = 'SELECT id,password FROM '.DB_PREFIX.'admin WHERE username="'.$username.'"';
    $result = $db->query($sql);
    $row = $result->fetch_assoc();
    $pass = $row['password'];
    if (password_verify($password,$pass)) {
        echo "Valid";
    }else{
        echo "Invalid";
    }
}

This is the password hashing and then save to DB

public function addnewadmin($username,$password)
{

    global $db;
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $sql = "INSERT INTO admin (username, password) VALUES ('".$username."', '".$hash."')";
    $result = $db->query($sql);

    return true;

}
Rohit Dhiman
  • 2,691
  • 18
  • 33

1 Answers1

0

Let's do this properly.

First, use prepared statements to get rid of SQL injection:

$stmt = 'SELECT id,password FROM '.DB_PREFIX.'admin WHERE username = ?';
$stmt->execute($username);

Then, and I guess that was the problem, fetch the result.

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$pass = $row['password'];

And now, you can verify the password.

Jules R
  • 553
  • 2
  • 18
  • `FROM ? admin` ? – Jonnix Dec 11 '18 at 08:36
  • Sure, though `FROM ?` won't always work. identifiers aren't generally allowed to use placeholders. – Jonnix Dec 11 '18 at 08:38
  • Does not work in [pdo](https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter) nor [mysqli](https://stackoverflow.com/questions/11312737/can-i-parameterize-the-table-name-in-a-prepared-statement) – DarkBee Dec 11 '18 at 08:39
  • I changed it already but still not working, when i tried to echo $pass it returns the value from the db – Kevin Dave Gerona Dec 11 '18 at 08:42