PHP检索记录的用户名并在页面中发布

时间:2014-04-30 16:09:20

标签: php mysql

我需要显示当前登录网站的用户名和注销表单。

我目前有这段代码:

<?php session_start();
$myusername = $_SESSION['myusername'];
if(isset($_SESSION[$myusername]) ){}
echo $myusername;
?>

myusername是表单文本框,username是MySQL表格行。

<html>
<head>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <header>
        <div class="header">
            <a href="#"><img class="logo" src="images/logo.png"></a>
            <h1 class="subtitle">Internal Systems</h1>
            <h4 class="slogin">Logged as: <?php session_start(); 
$myusername = $_SESSION['myusername'];
if(isset($myusername) ){ 
echo $myusername; 
}?> | <a href="/intse/logout.php">Logout</a></h4>
        </div>
    </header>

这是checklogin文件:

<?php

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="xxxxxx"; // Mysql password 
$db_name="intse"; // Database name 
$tbl_name="users"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT *, username FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
//session_register("myusername");
//session_register("mypassword"); 
$_SESSION['myusername'] = '$myusername';
$_SESSION['mypassword'] = '$mypassword';
header("location:sindex.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>

1 个答案:

答案 0 :(得分:0)

删除$_SESSION[]

中的变量
<?php session_start(); 
$myusername = $_SESSION['myusername'];
if(isset($myusername) &&  !empty($myusername)){ //check username is set
echo $myusername; 

}?>