Kent Godfrey Kent Godfrey - 5 months ago 11x
SQL Question

Notice: Undefined variable: username

My question = Why is there no value assigned to my $username when I try to use it in editor.php?

I have a log in system that works. Once the user logs in, I want to create a welcome line that says "Welcome [INSERT USERNAME HERE]". Currently, I am having issues with getting the echo to retrieve the variable "$username" since I get this error:

Notice: Undefined variable: username in editor.php on line 60.

Here is line 60 in editor.php. NOTE that editor.php is the page that the user is directed to once they have SUCCESSFULLY logged in

<h4>Welcome <?php echo $username;?> , to the editor.</h4>

The $username variable is declared in the loginAuth.php which is what runs when the user submits his/her login details on login.php.

Here is the relevant code for loginAuth.php:

ini_set('display_errors', 1);

//Connect to DB
include_once dirname(__FILE__).'/db_connect.php';
// PHP >= 5.3
include_once __DIR__.'/db_connect.php';

//starts session
if (isset($_POST['loginSub'])) {
//Variables declaration
$username = $_POST['user'];
$password = $_POST['password'];

//if username doesnt not equal empty space and password does not equal empty
space, then...
if(trim($username) != '' and trim($password) != ''){

//Sanitizes whatever is entered



//SQL query
$query = mysqli_query($conn, "SELECT * FROM users WHERE user='$username' AND
password = '$password' ")or die(mysqli_error($conn));
//applies msqli_num_rows to the $query. Counts how many rows
//if there is a row that matches what has been entered in form, then...
if($numrows > 0){

//initialize session
$_SESSION['login_user']= $username;
//take them to editor.php
header("location: editor.php"); // Redirecting To Other Page
echo "Username or password is incorrect.";
echo "Please enter information";

So basically, the editor.php page cant obtain the $username var for some reason because apparently it has no value...Eventhough my login page successfully works.

As requested, my HTML FORM in login.php:

<form id="login" method="POST" action="loginAuth.php">

<label for="user"><strong>Login:</strong></label>
<input type="text"size=20 autocorrect=off autocapitalize=words name="user">
<label for="password" > <strong>Password:</strong></label>
<input type="password" name="password">

<input name="loginSub" type="submit" value="Login">

Here are other questions have I research but have failed to apply to my own question:

Reference - What does this error mean in PHP?

PHP: "Notice: Undefined variable" and "Notice: Undefined index"


Your variable doesn't exists in editor.php

You need to get from your $_SESSION like this:


$username = $_SESSION['login_user'];
<h4>Welcome <?php  echo $username;?> , to the editor.</h4>