Login form does not recognize valid credentials

leokuz 0 Tallied Votes 370 Views Share

For some reasone everytime I enter either correct mine or someone else's valid email and password, I get message: Sorry, your credentials are not valid, Please try again.

What is wrong with this form?

<?php

// Grab User submitted information
$email = $_POST['email'];
$pass = $_POST['password'];

// Connect to the database
$con = mysql_connect('someremotehost','myusername','mypassword');
// Make sure we connected succesfully
if(! $con)
{
    die('Connection Failed'.mysql_error());
}

// Select the database to use
mysql_select_db('customers',$con);

$result = mysql_query('SELECT id FROM users WHERE email = $email AND password = $password');

if( mysql_num_rows($result) == 1 )
		{
			header('Location: forms.htm');
		}
else
    echo'Sorry, your credentials are not valid, Please try again.';
?>
broj1 356 Humble servant Featured Poster

You declared $pass variable but used $password in the query. And also you should check for existence of the data sent from the form and only if it exist query the database.

In additon to that you should use quotes when queryinig for strings.

And in addition to that you should clean the strings before sending them to the database to avoid injection attacks. So:

if(isset($_POST['email']) && isset($_POST['password'])) {
    $email = mysql_real_escape_string($_POST['email']);
    $password = mysql_real_escape_string($_POST['password']);

    ...

    $result = mysql_query("SELECT id FROM users WHERE email = '$email' AND password = '$password'");
}

And if I may add: you are using the almost obsolete mysql_* functions which are going to be kicked out of php soon. I strongly suggest you switch to mysqli API or PDO.

tpunt 0 Newbie Poster

Just to add onto what broj1 has said above, you should also be hashing the passwords instead of inserting them as plain text into your database. (In which case, you need not escape the password before inserting it because a harmless string - typically hexadecimal - would be produced by the hash).

It would also be more optimal to use MySQL's built-in COUNT() function when no result set needs to be returned for better performance.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.