Vyan Garcia Vyan Garcia - 4 months ago 17
PHP Question

Undefined Variable - Welcome [myusername]


Welcome
Notice: Undefined variable: myusername in C:\xampp\xamp\New folder\htdocs\login-form\login\login_success.php on line 6
no *


thats the error of my project when i tried to use this code. I want to add Welcome (username). I think theres an error in my login_success but i cant figure it out. Help me please

--------------checklogin.php---------------------------

<?php

ob_start();
$host="localhost";
$username="root";
$password="root";
$db_name="test";
$tbl_name="members";

mysql_connect($host,$username,$password)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");

$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

$myusername=stripslashes($myusername);
$mypassword=stripslashes($mypassword);
$myusername=mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE Username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

$count=mysql_num_rows($result);

if($count==1){

$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;

header("location:login_success.php");
}

else{

echo "Wrong Username or Password";
}
ob_end_flush();
?>


------------------login_success.php----------------------------

<li><a href="#">Welcome
<?php
session_start();
$_SESSION['myusername'] = $myusername;


if(isset($_SESSION['myusername']))
{
echo "ok";

}
else
{
echo "no";
}
?>

Answer

You need to check this line in login_success.php

$_SESSION['myusername'] = $myusername;

Here, you have already stored $_SESSION['myusername'] in the previuos page after login. This line indicates you're trying to overwrite the $_SESSION['myusername'] with $myusername.

But, our objective is to read $_SESSION['myusername'] and store it in $myusername. So, simply interchange the sides:

$myusername = $_SESSION['myusername']

Try this:

session_start();
$myusername = $_SESSION['myusername'];

if (isset($_SESSION['myusername'])) { 
    echo "User".$username." is logged in"; 
}  else { 
    echo "No user is logged in."; 
 } 

-checklogin.php--

$sql = "SELECT * FROM $tbl_name WHERE Username='$myusername' and password='$mypassword'";

$result = mysql_query($sql) or die(mysql_error());  // Check if you get any SQL syntax error
$count = mysql_num_rows($result); 
var_dump($count); // Check the value of $count
exit;