PHP Session变量问题

时间:2014-04-15 20:08:16

标签: php mysql

我遇到的问题是我们正在为项目使用PHP会话变量。为用户名存储变量的方式是,当用户使用用户名登录会话变量时,用户名登录。我需要从数据库中获取该用户名的id,并在登录用户的另一个页面上使用它。我甚至无法从会话变量中打印出用户名。我一直在努力奋斗,不知道该去哪里,我非常感谢你的帮助。我在第二个文件上添加了评论。我也不确定是否需要添加session_start();在每个我想使用会话变量的文件?一旦我在一个文件中收集变量,我可以在另一个文件中访问它吗?

此文件是登录文件:

<body>
<h1>Login</h1>
<form action="VerifyUser.php" method="post">
Username: <input type="text" name="userName"><br>
Password: <input type="password" name="pwd"><br><br>
<input type="submit" name="loginButton" value="Login"><br><br>
<a href="forgotPassword.php">
Forgot Password? Click Here!</a>
<a href="Registration.php"><br><br>
Need to Register? Click Here!</a>
</form>
</body>

这是在验证用户时发布的文件:(当我登录新页面时,仅打印&#34;工作&#34;来自提取POST之前的回声

<?php
    require_once('dbBaseDao.php');
    require_once('dbUserDao.php');
    $userDao = new dbUserDao();
    echo "<p>Working...</p>";
    extract($_POST);
    if( $userDao->{'verifyUser'}($userName, $pwd))
    {
        session_start();
        $_SESSION['userName'] = $userName;
        $result = $userDao->{'getUserByWhere'}("username ='" . $userName . "'");
        $user = mysql_fetch_array($result, MYSQL_ASSOC);

            print $userName;      //This is not printing

        $_SESSION['userId'] = $user['userId'];    //I think to get this I need 
//to query the database for whatever the username is here it is equal to that 
//in the database and get the userId from that, but I have no idea how to do this. 


        header('Refresh: 1;url=LoggedIn.php');
        exit();
    }
    else
    {
        header('Refresh: 1;url=LogIn.php');
        exit();
    }
?>

我的代码:这是我需要获取userId的地方,这样当我使用INSERT TO查询时,我可以根据userId选择游戏发送数据。

<?php include('header.php'); ?>

<?php

  require_once('dbBaseDao.php');
  require_once('dbUserDao.php');
  require_once('dbBotDao.php');

  $userDao = new dbUserDao();
  $botDao = new dbBotDao();

  session_start();
  $userID = $_SESSION['userId'];
  print $userID;


/*
* Description of code below: This code checks the name checkbox[] from the form in UpcomingGames.php for any
* selected games made by clicking on the checkbox and submitting the form. The first echo actually prints all
* the games selected by the user from UpcomingGames.php.
*/

 if(!empty($_POST['checkbox']))
  {
    foreach($_POST['checkbox'] as $check) 
    {
           echo "</br>";
           echo ($check);
           $userID = 2;

           $sql= "INSERT INTO UserPicks (userID, game) VALUES ('$userID','$check')";
           $result = mysql_query($sql);
           if (!$result) {
               $message  = 'Invalid query: ' . mysql_error() . "\n";
               $message .= 'Whole query: ' . $sql;
               die($message);
            }
    }
    echo "</br>";
    echo "</br>";
    echo "You predicted ";
    echo sizeof($_POST['checkbox']);
    echo " games to have upsets";
    echo "</br>";
    echo "</br>";
  }
?>

1 个答案:

答案 0 :(得分:3)

  

我也不确定是否需要添加session_start();在每个我想使用会话变量的文件上?

是的,您必须在访问这些会话所需的每个页面上使用session_start();