首页 > 解决方案 > 如果没有上传文件,如何编写 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');
    }

} 

标签: 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...
}

推荐阅读