php - 如果没有上传文件,如何编写 php 逻辑
问题描述
我想做一个更新个人资料页面。当用户上传图片时,它将更新到数据库并更改。$_SESSION['profilepic']
但是,如果用户不想更新其个人资料图像并且不更改数据库值而仅更改其他数据。我如何编写逻辑,如果“文件未上传,更新除图像之外的其他值并且不更改会话”,因为我无法将存储的 img 放置在输入文件值以确保数据库中的图像保持不变并且未更新
这是我的 php 代码:
if(isset($_POST['profile_update_btn']))
{
$username = $_SESSION['username'];
$profimage = $_FILES['profileimage']['name'];
$fullname = $_POST['fullname'];
$email =$_POST['email'];
$phone = $_POST['phonenum'];
$query = "UPDATE students SET fullName='$fullname',email = '$email', phoneNum='$phone', profilePic='$profiimage' WHERE email = '$username'";
$query_run = mysqli_query($connection,$query);
if($query_run)
{
move_uploaded_file($_FILES["profileimage"]["tmp_name"],"prof/".$_FILES["profileimage"]["name"]);
$_SESSION['profilepic'] = $profimage;
$_SESSION['success']= "Profile Updated";
header('Location: user_profile.php');
}
else
{
$_SESSION['status']= "Profile Not Updated";
header('Location: user_profile.php');
}
}
解决方案
当您上传文件时,您$_FILES
会在一个数组中填充值,其中包含文件名称字段的键。
'profileimage' =>
array (size=5)
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
实际值可能类似于:
'profileimage' =>
array (size=5)
'name' => string 'v35.doc' (length=7)
'type' => string 'application/octet-stream' (length=24)
'tmp_name' => string 'F:\wamp64\tmp\php37EA.tmp' (length=25)
'error' => int 0
'size' => int 45568
因此,您可以像这样执行逻辑:
if (empty($_FILES['profileimage']['name'])) {
//Do whatever you want when no upload...
}
推荐阅读
- java - REST API:URL 中的 JSON 对象以获取自定义 JSON
- akka - 类型为 2.6.3 的 akka 的日志记录问题
- python - 为什么我需要一个“返回”和一个新变量?
- ios - Fabric crashlytics 显示错误:致命异常:NSInternalInconsistencyException。在 IOS 应用程序中
- r - 如何从因子存储中提取特定值作为数据框中的列值
- kubernetes - kubelet 错误:更新节点租约失败
- javascript - XMLHttpRequest | 手动发送请求会得到 2111 个字符的响应,但使用 XMLHttpRequest 响应的长度为 179
- python-3.x - SyntaxError:python套接字编程中listen()的语法无效
- javascript - Reactjs如何从另一个JavaScript文件导入常量数组
- ios - 枚举案例“案例”不是“类型”类型的成员