将用户 ID 设置到会话数组中的方式


Set userid into the session array how?

>您好,我正在发布有关此问题的第 4 个问题,但到目前为止没有人可以帮助我,所以让我们从头开始,我需要的很简单,我需要: 将 userID 变量从名为"users"的表中的列名"userID"设置到 Sessions 数组中: $_SESSION['userID']

这是我的登录页面代码:

<?php 
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
    <?php 
    //else look at the database and see if he entered the correct details
    } else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];

这是作函数登录的用户类:

public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();  

$result = $sth->fetch(PDO::FETCH_ASSOC);
$success = true;
if ($result!==false) { // Check there is a match
    $_SESSION['userID']= $result['userID'];
}

$success = true;
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;

代码工作正常,我只想添加加法,它将从数据库内用户表的列中获取 userID 值,并在用户登录后将其存储到 $_SESSION['userID']。

所以知道如何在我的代码中达到这个目标吗?谢谢!

如果您只想从表中获取 UserID,则必须先执行$stmt->fetch()来加载它,然后才能将其存储在 SESSION 中。

因此,在执行后function userLogin()执行以下操作:

$result = $stmt->fetch(PDO::FETCH_ASSOC);

如果找到用户$result则将包含用户表中的所有字段。所以:

if ($result!==false) { // Check there is a match
    $_SESSION['userID']= $result['userID'];
}