I have a form named login
that when is submitted sends the fields username
and password
to a MySQL database to check if they match. I want to echo
an error when they don't match.
Here is the PHP code that goes above the form:
if (!isset($_POST['login'])) {
mysql_connect (...);
mysql_select_db (...);
$username = $_POST['username'];
$password = $_POST['password'];
$location = $_POST['location'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM members WHERE username='$username' and password='$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
session_register("username");
session_register("password");
header("Location: $location");
}
else {
echo "Wrong username or password.";
}
mysql_close();
}
And the form:
<form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="location" type="hidden" value="<?php echo $_GET['location']; ?>"/>
<input name="username" type="text" value="Username" onclick="this.value=''"/>
<input name="password" type="text" value="Password" onfocus="this.value='';this.type='password'"/>
<input name="submit" type="submit" value="Login"/>
</form>
If I submit the form with the correct username and password the code works normally.
The problem is that the error message is always present, even before the form is submitted. Any ideas?