PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hi i was just wondering if anyone could tell me why i get this javascript alert when the username is entered wrong but it just refreshes page when the password is entered wrong and doesnt display error? Heres the code:
// Check matching of username and password.
$result=mysql_query("select username, password from users where username='$username' and password='$md5_password'");
while($row = mysql_fetch_array($result)) {
$user = $row['username'];
$password = $row['password'];
if( ($username==$user) AND ($password==$md5_password) ) { // If match.
session_register("username"); // Craete session username.
header("location:index.php"); // Re-direct to main.php
exit;
}
else { // If not match.
echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";
}
}
The code in the while block will only run if there is a result from your query (which would only happen if both the username and password are correct).
This would trigger the alert if either the username and password don't match:
$result=mysql_query("select username, password from users where username='$username' and password='$md5_password'");
if(mysql_num_rows($result) == 1) { // then there is a row with matching username and password hash
// don't need to check username and password again
session_register("username"); // Craete session username.
header("location:index.php"); // Re-direct to main.php
exit;
}
else {
echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";
}
You should also add LIMIT 1 to the end of your query
I also don't understand why it is you have checked the username and password in the while loop, since they are already checked in the query, and will only ever reach the while if they match up already. You are basically authenticating the same data twice which is pointless