mysqli回显用户数据

时间:2014-10-13 10:51:43

标签: php mysql mysqli

我有这个用于数据库连接的php,我试图在home.php中回显用户数据(登录用户的用户名)

    <?php

  session_start();

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="browser"; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($con,"test") or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($con, $myusername);
$mypassword = mysqli_real_escape_string($con, $mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($con, $sql);

// Mysql_num_row is counting table row
$count=mysqli_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['username']= "username";
$_SESSION['password']= "password";
header("location:home.php");
}
else {
echo "Wrong Username or Password";
}
?>

现在在home.php上我想回显登录用户的用户名

 <?php
session_start();
if(!$_SESSION['username']= "username"){
header("location:main_login.php");
}
?>

<html>
<body>
<h1>Logged in Successful</h1>
as 

<?php echo $data['username']; ?>!

</body>
</html>

我该如何调用此功能?

4 个答案:

答案 0 :(得分:0)

你的$data未声明的变量在这里没有任何意义。

您必须更改此行:<?php echo $data['username']; ?>

收件人:<?php echo $_SESSION['username']; ?>

答案 1 :(得分:0)

只需echo $_SESSION['username'],无需做任何其他事情。

答案 2 :(得分:0)

@ user3487121

由于您已将用户数据存储到会话中,因此您需要在下面编写代码来打印用户名。

<?php echo $_SESSION['username']; ?>

答案 3 :(得分:0)

将您的第二个代码更改为:

<?php
    session_start();
    if(!($_SESSION['username'] == "username")){
        header("location:main_login.php");
}
?>

<html>
<body>
<h1>Logged in Successful</h1>
as 

<?php echo $_SESSION['username']; ?>!

</body>
</html>

首先注意if(!$_SESSION['username'] == "username"){

您使用operator =检查会话中的值是否等同于&#39; username&#39;,但为此您需要使用==。

Comparsion operators(manual)

All operators(manual)