如何在当前登录的用户帐户中插入图像名称?

时间:2019-03-06 06:25:42

标签: php mysql

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

auth.php

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

home.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;


?>

2 个答案:

答案 0 :(得分:1)

只需两个修改就可以完成:

1)您必须从会话中获取当前用户的名称

$userId = $_SESSION['username'];

2)在查询的username值中添加单引号。

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

注意:

  

如果您要为数据库查询提供一个值,如果它是非数字的,   您需要在其中添加单引号。

     

这表明传递的字符串是一个值,而不是任何MySQL   保留字/数据库名称/表名称/字段名称。

答案 1 :(得分:1)

用户登录后,必须保持其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>  ';
}