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?
change first line to :
if (isset($_POST['username'])) {
if (!isset($_POST['login']))
remove the exclamation mark. So if (isset($_POST['login']))
$_POST['login'] is most likely not set in your script. The aforementioned solution will fix your first bug. Yet, you will not be able to login if $_POST['login'] is not set.
I suggest you check for the post variables that you will use in your script:
if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['location'])) {
// your code
}