未定义的变量 - 欢迎[myusername]

时间:2016-07-24 03:38:08

标签: php session

  

欢迎   注意:未定义的变量:第6行的C:\ xampp \ xamp \ my文件夹\ htdocs \ login-form \ login \ login_success.php中的myusername   没有*

当我尝试使用此代码时,这是我项目的错误。我想添加欢迎(用户名)。我认为我的login_success中出现了错误,但我无法弄明白。请帮帮我

-------------- 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"; 
     } 
?>  

3 个答案:

答案 0 :(得分:1)

您需要在login_success.php

中查看此行
$_SESSION['myusername'] = $myusername;

此处,您已在登录后的previuos页面中存储了$ _SESSION ['myusername']。此行表示您尝试使用$ myusername覆盖$ _SESSION ['myusername']。

但是,我们的目标是阅读$ _SESSION ['myusername']并将其存储在$ myusername中。 所以,简单地交换双方:

$myusername = $_SESSION['myusername']

试试这个:

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;

答案 1 :(得分:0)

$_SESSION['myusername'] = $myusername;

您正尝试将$myusername的值分配给$_SESSION['myusername']

但你必须做相反的事情。

$myusername = $_SESSION['myusername'];

答案 2 :(得分:0)

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

if (isset($_SESSION['myusername'])) { 
    echo "User".$username." is logged in"; 
}
如果$_SESSION['myusername']为空/空,如果您不想显示任何内容,请

省略else部分。