chris chris - 13 days ago 4x
MySQL Question

PHP check password script wont work for more than one user

I am trying to create a simple login credentials checker (with session variables).

this is what i have so far:

$u_name = mysql_real_escape_string($_POST['uname']);
$p_word = mysql_real_escape_string($_POST['pword']);
# *** querying all records ***
$query = mysql_query("SELECT valid_username, valid_password FROM notes_users");
while($rst = mysql_fetch_array($query)) {

//echo $rst[valid_username] . ", ";
//echo $u_name . " || ";
//echo ($rst[valid_username] == $u_name) . " || ";
//echo $rst[valid_password] . ", ";
//echo $p_word . " || ";
//echo ($rst[valid_password] == $p_word) . " || ";
//echo (($rst[valid_username] == $u_name) AND ($rst[valid_password] == $p_word));
//echo "<br/>";

if (($rst[valid_username] == $u_name) AND ($rst[valid_password] == $p_word)) {
$_SESSION['login'] = "1";
header('Location: main.php') ;
} else {
$_SESSION['login'] = '';
header('Location: badlogin.php') ;



here is the issue: If the MySQL table has more than one user in it's list, the check breaks. only the last-entered user in the table has access granted. anyone above the last user entered gets bumped to the incorrect login screen- even when the credentials are correct. why is this happening? can anyone suggest a code fix or better code to implement this login check?

edit: the comment code tests to see if the credentials supplied match those on record. that part of the script works fine.

problem solved! thank you all. for anyone who sees this in the future, definitely encrypt your passwords, mine are plain text because this is a local test application and wont even see an upload to the net.


There is no need to loop through all your user records. Imagine if you would have a database with 1000000 users, you will only need to try fetching the record that corresponds to the supplied username and password. Update your query to something like this:

$query = mysql_query("SELECT * FROM notes_users 
                      valid_password = '$p_word' && 
                      valid_username = '$u_name'");

Then you would do something like:

if (($row = mysql_fetch_array($query)) {
   // valid user
} else {
   // invalid password or username