Search code examples
phpundefined-index

Notice: Undefined index: username on line 10


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");

}

?>

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.