Skip to content
Advertisement

Trying to compare values from database and php file

I’m having trouble trying to compare my entries in a database with a php file, I have a connection and I’m getting results but I can tell I’m grabbing the whole list of entries and trying to compare the entire table with individual results. I’m just trying to create a simple Login page nothing flashy, here’s my code:

<?php
// Get the user data
$credential_email = filter_input(INPUT_POST, 'email');
$credential_password = filter_input(INPUT_POST, 'password');

// Validate inputs
if ($credential_email === null || $credential_password === null) {
    $error = "Invalid credential data. Check all fields and try again.";
    include('error_2.php');
} else {
    require_once('database.php');
// compares values entered in login page form with mySQL database, and then directs either to protected page or to a failure page
$query = "SELECT * FROM credentials ORDER BY email";
$statement = $db->prepare($query);
$sel = $statement->execute();
$statement->closeCursor();
if($credential_email===$sel['email'] && credential_password===$sel['password'])
{
echo"success";
}
else
{
echo"failure";
}
}
?>

I’m posting the right information into email and password in the previous php file before submitting and it matches in the database so that’s correct but I keep getting failure outputted. Any ideas?

Advertisement

Answer

Database are good at fetching and comparing information. So SELECT password FROM credentials WHERE email = :email is the query you should be using. Retrieving * can be inefficient so get in the practice as retrieving only what you use.

Read how to prevent SQL injection as this should be parametrized.

A list will still be returned from the SQL query, however if email is unique (recommended), there should only be only entry.

so:

$query = "SELECT password FROM credentials WHERE email = :email";
$statement = $db->prepare($query);
$sel = $statement->execute(array(':email' => $credential_email));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if (password_verify($credential_password, $result['password'])) ...

Don’t store plain text passwords. Use password_hash like this answer.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement