无法在PHP中设置会话cookie

时间:2013-12-03 15:11:15

标签: php mysql session-cookies

我一直在尝试在成功登录后设置会话cookie。这些cookie 部分有效,但是我在从数据库表中读取值并将其分配给会话cookie时遇到了问题

当我在后面的页面中设置$_SESSION["User_ID"] = 'test'并回显会话cookie时,它工作正常并显示测试。但是,使用$row["User_ID"];我无法使其工作 - 它没有显示任何值,因此可能不会读取值。谢谢你们。

整个登录代码:

<?php
    session_start();

    $server = "*****.com";
    $schema = "*****";
    $uid = "******";
    $pwd = "******";

    $username =$_POST["txt_username"];
    $password =$_POST["txt_password"];

    mysql_connect($server , $uid , $pwd) or die ("server not found");
    mysql_select_db($schema) or die ("Database not found");

    $sql = "SELECT User_ID, Username, Password, User_Level
            FROM Account
            WHERE Username = '$username' AND  Password = '$password'";

    $record = mysql_query($sql);
    $row = mysql_fetch_array($record);

    if(mysql_num_rows($record) == 0)
    {
        die(header("location: LoginFailed.html"));
    }
    else if(mysql_num_rows($record) == 1)
    {
        $row = mysql_fetch_array($record);
        $_SESSION["User_ID"] = $row["User_ID"];
        $_SESSION["User_Level"] = $row["User_Level"];
        header("location:Home.html");

    }
    else
    {
        $row = mysql_fetch_array($record);      
        $_SESSION["User_ID"] = $row["User_ID"];
        $_SESSION["User_Level"] = $row["User_Level"]; 
        header("location: Home.html");
    }

    mysql_close();

?>

2 个答案:

答案 0 :(得分:2)

在您的代码中,您拨打$row = mysql_fetch_array($record);两次。 我想如果你先删除$row = mysql_fetch_array($record);,那么你的代码就可以了。

答案 1 :(得分:1)

如果删除第一个mysql_fetch_array()不起作用,则还有另一个问题

我可以告诉你这段代码:

<?php
    session_start();

    $server = "*****.com";
    $schema = "*****";
    $uid = "******";
    $pwd = "******";

    $username =$_POST["txt_username"];
    $password =$_POST["txt_password"];

    mysql_connect($server , $uid , $pwd) or die ("server not found");
    mysql_select_db($schema) or die ("Database not found");

    $sql = "SELECT User_ID, Username, Password, User_Level
            FROM Account
            WHERE Username = '$username' AND  Password = '$password'";

    $record = mysql_query($sql);
    $row = mysql_fetch_array($record);
    print_r($row);

使用您的原始登录信息和用户名adam和密码a将得到以下结果:

Array
(
    [0] => 16
    [User_ID] => 16
    [1] => adam
    [Username] => adam
    [2] => a
    [Password] => a
    [3] => 2
    [User_Level] => 2
)

您确定发布的值是txt_username和txt_password(执行print_r($ _ POST))以确定。

需要注意的事项:

  1. 您可以使用预先准备好的语句或至少引用您的输入
  2. 使用某种哈希密码可以使用盐和胡椒,但不要以明文形式存储
相关问题