将user_id存储在会话变量中

时间:2018-01-17 14:20:16

标签: php mysql

所以我有这个网站,司机可以登录并注册。

目前我可以将用户名存储在会话变量中,我尝试对user_id执行相同的操作,以便用户以后可以在添加作业的更多详细信息时检索它。 继承了我到目前为止所得到的:

function selectUser($conn, $username, $password, $userID)
{
    $query = "SELECT * FROM login WHERE username = :username"; 
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':username', $username);
 //$stmt->bindValue(':user_ID', $userID);
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_OBJ))
    {

        if (md5($password) == $row->password) {  
            $_SESSION['username'] = $username;
            $_SESSION['user_ID'] = $userID;
   //       $_SESSION['password'] = $password;
            echo "Welcome, you are now logged in as " . $username; 
            return true;
        }



        return false; 
    }
    else
    {
        //echo "Your details were not found";
        return false;
    }
}

当驱动程序访问另一个页面时:

<?php
     if(!isset($_SESSION)) 
{ 
    session_start(); 
}   

require_once ("config.inc.php");

try
    {
    $conn = new PDO(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD);
    }

catch(PDOException $exception)
    {
    echo "Oh no, there was a problem" . $exception->getMessage();
    }

if(isset($_SESSION["username"]))
{
    echo "Welcome, you are now logged in as <b>".$_SESSION['username']."</b> <img class='clientView' src='images/loginIcon.png' alt='client'>"; }
    else { 
    echo "You are currently not logged in";
    }


    $login = $_SESSION['user_ID'];

$query = "SELECT * FROM login WHERE user_ID = :login"; 

$term = $conn->prepare($query);
$term->bindValue(':login', $login);
$term->execute();

$login = $term->fetch(PDO::FETCH_OBJ);
    print_r($_SESSION); 
    ?>

使用print r测试它,由于某种原因它似乎没有收集user_ID。

我做错了什么?

经过测试:https://snag.gy/6bGd5m.jpg

调用函数时:

$username=trim($_POST['username']);
$password=$_POST['password'];

$username= htmlspecialchars($username);
$validForm = true;

if (empty($_POST["username"]))
            {
            $validForm=false;
            }
if (empty($_POST["password"]))  
            {
            $validForm=false;
            }
if (!$validForm) {

$error = "please ensure all fields are filled in";
include("add.php");
return false;

}           


$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{

       header( 'Location: profile.php');
}else{
       $error = "The details you have entered are incorrect";
      include("add.php"); 
}

1 个答案:

答案 0 :(得分:1)

调试。

您将值存储在会话状态中的哪个位置?:

$_SESSION['user_ID'] = $userID;

好的,那么$userID来自哪里?:

function selectUser($conn, $username, $password, $userID)
{
    //...

好的,那么函数参数来自哪里?:

selectUser($conn,$username,$password)

无处。您从未提供要存储在会话中的值,因此会话中没有存储任何值。

您似乎不太可能提供该功能的用户ID。相反,您可能想要提供您当前所做的用户名和密码,然后从数据库中获取用户ID。可能看起来更像这样:

$_SESSION['user_ID'] = $row["user_ID"];

或者也许:

$_SESSION['user_ID'] = $row->user_id;

或者您从$row对象获取值。

但基本上这里的重要教训是......当一个值不是你所期望的那样时,追溯那个值的来源。你可能在某处有一个错误的假设。