php - 在 PHP 中使用 session ID 作为用户名 INSERT

标签 php mysql

目前正在尝试运行一个查询,我已经成功地通过添加确切的用户名使其正常工作,但是当我尝试使用当前查询来使用 $_Session 标识的用户名时,它不起作用。

<?php 
    include ("config.php"); 
    session_start();    
    $username = $_SESSION['username'];
    $stmt = $db->exec ("UPDATE users SET lastlogindate = NOW() WHERE username = '$username'");
?>

编辑 - Login.php 代码

<?php 
    require("config.php"); 
    $submitted_username = ''; 
    if(!empty($_POST)){ 
        $query = " 
            SELECT 
                id, 
                username, 
                password, 
                salt, 
                email 
            FROM users 
            WHERE 
                username = :username 
        "; 
        $query_params = array( 
            ':username' => $_POST['username'] 
        ); 

        try{ 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); } 
        $login_ok = false; 
        $row = $stmt->fetch(); 
        if($row){ 
            $check_password = hash('sha256', $_POST['password'] . $row['salt']); 
            for($round = 0; $round < 65536; $round++){
                $check_password = hash('sha256', $check_password . $row['salt']);
            } 
            if($check_password === $row['password']){
                $login_ok = true;
            } 
        } 

        if($login_ok){ 
            unset($row['salt']); 
            unset($row['password']);
            $_SESSION['user'] = $row;
            header("Location: main.php"); 
            die("Redirecting to: main.php");    
        } 
        else{ 
            print("Login Failed."); 
            $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); 
        } 
    }; 
?>  

最佳答案

你设置$row进入$_SESSION['user']在 login.php 中,然后通过 $_SESSION['username'] 获取它错误地,你应该使用 $_SESSION['user']相反。

试试这个:

<?php
    include ("config.php"); 
    session_start();    
    $username = $_SESSION['user'];
    $stmt = $db->prepare("UPDATE users SET lastlogindate = NOW() WHERE username = ?");
    $stmt->bindParam(1, $username['username']);
    $stmt->execute();
?>

关于php - 在 PHP 中使用 session ID 作为用户名 INSERT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19986723/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 用 php 数据库中的数据填充组合框

PHP 开关,为什么这不起作用?

php - 使用 SSL 使用 PHP 连接到 EPP 服务器

php - 查找连接 3 个表的 mysql 表中最后一篇文章的用户名

MySQL同一查询多个表

mysql - 子查询返回多列

mysql - 如何只在满足特定条件的情况下现场下订单?

mysql - 通过在sql中对多个列进行分组来查找列中的最小值

mysql - 从 MySQL 查询生成数据库架构图的工具