php - 我如何在当前登录的用户帐户中插入图像名称?
问题描述
当我使用插入到所有用户行中的此脚本图像名称时。我如何插入当前会话用户的行
授权文件
<?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;
?>
解决方案
当用户登录时,您必须保持他们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> ';
}
推荐阅读
- mongodb - ReferenceError:Github Actions Jest 脚本中未定义 TextEncoder
- solr - 添加自定义 Cql3SolrSecondaryIndex 后无法使用 Stargate 进行查询
- python - Python/Heroku Spotify .cache 存档问题
- unicode-string - unicode 字符 u+80 - u+BF 有效吗?
- c++ - 使用 Eigen::Matrices 的向量容器。为什么?
- ruby-on-rails - 处理资源关联的最佳方式
- apache-spark - 火花任务上下文。partitionId() 与 TaskContext.get().partitionID()
- python - 如何使用 `pip` 从 github 链接安装额外要求
- visual-studio - 我不应该上传什么到 GitHub?
- typescript - 打字稿:通用地图
值类型