Question

I get this error when I ran my php code! any help on what I need to do to fix it?

Notice: Undefined index: username in C:\xampp\htdocs\Slamza\login.php on line 10

Notice: Undefined index: password in C:\xampp\htdocs\Slamza\login.php on line 11

My code is

    <?php

session_start();



$username = $_SESSION['username'];


$username = $_POST['username'];
$password = $_POST['password'];

include("connect.php");

if ($username && $password)

{


$queryget = mysql_query("SELECT * FROM users WHERE username='$username' AND     password='$password'");
$numrows = mysql_num_rows($queryget);
if ($numrows != 0) 

{


    $_SESSION['username'] = $username;

    echo "You have been logged in!";


}


else

{

    echo "You have not been logged in";

}





}

else

{

echo "You didn't provide the information needed to login";
include("index.php");

}

?>
Was it helpful?

Solution

Since your code is already checking for missing $username and $password data here is what you can do to keep the same code and execution flow

$username = isset($_SESSION['username']) ? $_SESSION['username'] : NULL;

$username = isset($_POST['username']) ? $_POST['username'] : $username;
$password = isset($_POST['password']) ? $_POST['password'] : NULL;

Also, as others have pointed out if you are submitting this $_POST data from a form you might have to check the $_POST["submitButtonName"] value as well.

OTHER TIPS

You need to check the submit button with isset, and then also to check the post of username and password with isset.

Because in this way that you done, you didn't have defined the post data.

It appears that the post information is not being sent to the PHP script. You could check first to make sure that the data is being sent:

if( !isset( $_POST['username'] ) || !isset( $_POST['password'] ) ) die( "Incomplete data sent." );

But this will only check to see if the data was sent. You could also do print_r( $_POST ) to see which variables are being sent to your script. It would be useful to take a look at your form where this data is being entered. Perhaps you are using GET instead of POST, or your apache configuration is not setup correctly to send data through POST.

Always check if the form was submitted. Use isset() for that purpose:

if( isset($_POST['submitButton']) ){

if( !isset($_POST['username']) || !isset($_POST['password']) ) {
    echo "Please fill all the fields!";
}

Note that submitButton here is the name attribute of the input button in your form.

<input type="submit" name="submitButton"/>

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top