PDO:isset&会话无法正常显示

时间:2013-12-21 07:44:43

标签: php mysql pdo

我很难在用户登录后显示用户的信息。

这是我的index.php文件:

<?php
require 'core/db/connect.php';

    if(isset($_SESSION['username'])){
        include 'includes/menu.php';
    }
    else{
        echo '<a href="register.php">Register</a><br />';
        echo '<a href="login.php">Login</a><br />';
    }
?>

对于profile.php,每当我回应一些东西时,它都不会回显:

<?php 
if(isset($_SESSION['username'])){
    include 'core/db/connect.php';

    $username = $_SESSION['username'];

    $query = dbConnect()->prepare("SELECT username FROM users WHERE username = :username");
    $query->execute(array(':username' => $username));
    $row = $query->fetch();

    echo 'Logged in as: ', $row['username'];
}

?>

这是我的第一个脚本,很抱歉!

如果这有帮助,这是我的login.php:     

<form method="POST">
<input type="text" name="username" placeholder="username"><br/>
<input type="password" name="password" placeholder="password"><br />
<input type="submit">
</form>

<?php
    if(isset($_POST['username'], $_POST['password'])){
    require 'core/db/connect.php';

    $query = dbConnect()->prepare("SELECT username, password FROM users WHERE username = :username AND password = :password");
    $query->execute(array(
        ':username' => $_POST['username'], 
        ':password' => $_POST['password']
    ));

    if($query){
        header('Location: index.php');
    }
    else{
        echo 'Username or Password is wrong.';
    }
}
?>

2 个答案:

答案 0 :(得分:1)

在PHP中使用会话之前,您必须致电session_start();

答案 1 :(得分:0)

在您的代码中,您在connect.php中启动session_start()。这意味着,您在会话开始之前阅读$ _SESSION ['username']。

要解决此问题,您需要在读取$ _SESSION变量之前调用session_start()。 尝试更改您的代码:

<?php 
if(isset($_SESSION['username'])){
    include 'core/db/connect.php';

为:

<?php

session_start();
if(isset($_SESSION['username'])){
    include 'core/db/connect.php';