首页 > 解决方案 > 我如何在当前登录的用户帐户中插入图像名称?

问题描述

当我使用插入到所有用户行中的此脚本图像名称时。我如何插入当前会话用户的行

授权文件

<?php
session_start();
if(!isset($_SESSION["username"]) ){
header("Location: login.php");
exit(); }
?>

主页.php

    <?php

include("php-includes/auth.php");  



//Include database configuration file
include_once 'php-includes/dbConfig.php';

//Get current user ID from session
$userId = $_SESSION["username"];

//Get user data from database
$result = $db->query("SELECT * FROM user WHERE username = $userId");
$row = $result->fetch_assoc();

//User profile picture
$userPicture = !empty($row['picture'])?$row['picture']:'no-image.png';
$userPictureURL = 'uploads/images/'.$userPicture;


?>

标签: phpmysql

解决方案


当用户登录时,您必须保持他们username的会话状态,您可以使用下面给出的代码......

<?php
session_start();
//retrive username from database and then save in session
$_SESSION['username'] = $username;

当您到达此脚本时,您需要在其中插入该用户的图像 这里可以从如下所示的会话中获取用户名...

session_start();
$userId = $_SESSION['username'];

然后在你的 MySQL 查询中使用它

$update = $db->query("UPDATE user SET picture = '$fileName' WHERE username = '$userId'");

另外,请记住,当您使用双引号 (") 进行数据库查询时,您不需要在变量名周围使用点。而单引号就足够了

完整的代码如下...

if(!empty($_FILES['picture']['name'])){
    //Include database configuration file
    include_once 'php-includes/dbConfig.php';

    //File uplaod configuration
    $result = 0;
    $uploadDir = "uploads/images/";
    $fileName = time().'_'.basename($_FILES['picture']['name']);
    $targetPath = $uploadDir. $fileName;

    //Upload file to server
    if(@move_uploaded_file($_FILES['picture']['tmp_name'], $targetPath)){
         session_start();
        //Get current user ID from session
        $userId = $_SESSION['username'];
        $update = $db->query("UPDATE user SET picture = '$fileName' WHERE username = '$userId'");

        //Update status
        if($update){
            $result = 1;
        }
    }

    //Load JavaScript function to show the upload status
    echo '<script type="text/javascript">window.top.window.completeUpload(' . $result . ',\'' . $targetPath . '\');</script>  ';
}

推荐阅读