在php mysqli中更新其他记录时删除了图像

时间:2018-10-18 08:10:39

标签: php image mysqli sql-update

在更新记录时,如果我不上传图像,然后单击“更新”按钮,则将删除当前图像。
这是代码

<?php

if (isset($_POST['update_record'])){

    $edit_id = $_GET['edit'];
    $username  = $_POST['name'];
    $email  = $_POST['email'];
    $city  = $_POST['city'];


    $file_name = $_FILES['file']['name'];
    $file_tmp_name = $_FILES['file']['tmp_name'];
    $file_error = $_FILES['file']['error'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];

    $allowed = ['png' , 'jpg' , 'jpeg'];
    $pathinfo =   pathinfo($file_name , PATHINFO_EXTENSION);

    $destination = "uploads/" . $file_name ;

    if (in_array($pathinfo , $allowed)){
        if ($file_size < 100000){
            if ($file_error === 0){

                move_uploaded_file($file_tmp_name, $destination) ;
            } //error close here
            else{
                echo "Some kind of error";
            }
        } //size close here

        else{
            echo "File Size is too big!";
        }
    } //type close here

    else{
        echo "File type is wronng";
    }

    $update_query = "UPDATE crud 
                        SET `name`='$username' , `email`='$email' ,
                             `city`='$city', `image`='$destination' 
                     WHERE id=$edit_id";

    $run = mysqli_query($connect, $update_query) ;

    if ($run){
        header("Location: show_record.php") ;
    } else{
        echo "Error in Updating the data";
    }

} //main if isset close here
?>

1 个答案:

答案 0 :(得分:0)

在继续操作之前,验证文件是否存在。如果没有文件,则不要在更新查询中更新$destination

//use a flag
$fileExists = false;

if(!empty($_FILES['file'])) { //check here
$fileExists = true;
 //rest of the file upload code    
}


if($fileExists === true){
  // a file was uploaded. now update $destination variable in update query as well
}