PHP echo Localhost返回值“0”

时间:2016-08-18 11:10:53

标签: php session-variables

我正在创建一个具有注册/登录功能的网站,并希望该页面在通过网站的多个元素登录后显示用户名。获取客户端信息有三个主要部分,登录页面(只是一个帖子方法表单),验证密码和数据库电子邮件的验证页面,还设置会话变量,然后是欢迎页面回显名称,但只有echo的值为“0”。

验证脚本是:

<?PHP
//Start a session
session_start();

//Connect to the database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("PhoneBro") or die(mysqli_error());

//Assign varibales to input data
$email = $_POST['email'];
$password = md5($_POST['password']);

//Query database to check information
$query = mysql_query("SELECT * FROM Customers WHERE Email='$email' AND Password='$password'") or die();

//Remember information about user to use later
$_SESSION['name'] = mysql_query("SELECT FirstName FROM Customers WHERE Email='$email'") or die();

//Validate login or redirtect if incorrect
if (mysql_num_rows($query)>0){
    header('location: loginSuccess.php');
    exit();
}else{
    header('location: loginFail.php');
    exit();
};
?>

欢迎页面的代码:

<?PHP 
session_start();
?>
    <!DOCTYPE html>
    <html>

    <head>
        <title>PhoneBro | Welcome Back</title>
    </head>

    <body>

        <div class="center">
            <p>Welcome back,
                <?PHP
                echo $_SESSION['name']; ?>
            </p>
            <a href="signOut.php">
                <button>Sign Out</button>
            </a>
        </div>
    </body>

    </html>

查询中的拼写对数据库是正确的,因为它成功地验证了用户名和密码,我无法想象为什么它也不会返回FirstName查询的任何值。 请询问是否需要更多信息。

1 个答案:

答案 0 :(得分:2)

$_SESSION['name']是&#34; 0&#34;因为遗漏了一些像mysql_fetch_array()

尝试更改

$_SESSION['name'] = mysql_query("SELECT FirstName FROM Customers WHERE Email='$email'") or die();

$db_result = mysql_query("SELECT FirstName FROM Customers WHERE Email='$email'") or die();
$db_row = mysql_fetch_array($db_result);
$_SESSION['name'] = $db_row["FirstName"];