Search code examples
phpphpdesigner

when password and username match in DB, Error show up?


when write anything in form and click Enter button, there is no error, but when i write the username and password correct the error show up i tried echo "$_POST['username']"; // print username if username doesn't match ?

Error:

Notice: Undefined index: username in ..

Notice: Undefined index: password in ..

this is my form

<form action="2.php" method="post">


<table align="center">
    <tr>
    <td>Username</td>
    <td><input type="text" name="username" /></td>
    </tr>
    <tr>
    <td>Password</td>
    <td><input type="password" name="password" /></td>
    </tr>
    <tr>
    <td colspan="2" align="center"><input type="submit" value="Enter"  />
    </td>
    </tr>
</table>
</form>

and this my second page

<?php
$username = mysql_real_escape_string($_POST['username']); 
$password = mysql_real_escape_string($_POST['password']);

    $connection = mysql_connect('localhost', 'root', '');
    if (!$connection){
        die('Could not connect');
        exit; 
    }
    mysql_select_db('dbName') or die( "Unable to select database");

    $query = "SELECT * FROM admin WHERE username = '$username'";

    $result = mysql_query($query) or die(mysql_error());

    $num = mysql_num_rows($result); // number of rows

    if ($num > 0){
    $i = 0;
    while ($i < $num){


        $row = mysql_fetch_array($result);

        if ( ($password) == $row['password'] && ($username) == $row['username'] ){

            header('location:2.php');

            $_SESSION['sessionname'] = $username;
            $_SESSION['sessionpass'] = $password;
        }

        elseif ( ($password) != $row['password'] && ($username) == $row['username'] ) {
            echo "Wrong Password <a href='1.php' >Click Here</a>";

        }

        $i++;
        }
    }else {
        echo "Username  <strong><u>$_POST[username]</u></strong> invalid ! <a href='1.php' >Click Here</a> ";


        }
    ?>

Solution

  • There is no reason to assign the username and password variables in the way you did. Simply assign the post data to the variables as you normally would with a session.