如果上传则更新图像否则使用预先存储的图像

时间:2018-06-18 11:25:11

标签: php database

<?php

include '../db_conx.php';

$id = $_POST['id'];   

$file = addslashes(file_get_contents($_FILES["college_image"]["tmp_name"]));


$insert_data1 = mysqli_real_escape_string($db_conx,$_POST['college_overview']);
$insert_data2 = mysqli_real_escape_string($db_conx,$_POST['college_courses']);
$insert_data3 = mysqli_real_escape_string($db_conx,$_POST['college_facilities']);

$test = "UPDATE college_details SET college_overview='$insert_data1', college_courses='$insert_data2', college_facilities='$insert_data3',college_image = '$file' where id = '$id' ";
if (mysqli_query($db_conx,$test)){
    header("Location:college.php?success");
}
{
    echo("Error description: " . mysqli_error($db_conx));
}
?>

每当我尝试更新而不上传新图像时,先前存储的图像将被删除。如何在没有文件上传的情况下保留旧图像

1 个答案:

答案 0 :(得分:0)

您可以使用简单的if else语句检查上传文件是否为空,并相应地重新格式化您的sql语句:

if(!file_exists($_FILES["college_image"]["tmp_name"]) ||
 !is_uploaded_file($_FILES["college_image"]["tmp_name"])) {
   $test = "UPDATE college_details SET college_overview='$insert_data1',
              college_courses='$insert_data2', college_facilities='$insert_data3', 
              where id = $id ";
 //No file is uploaded, we skip updating the image.
}else{
   //Upload File is there, we update the image file in the database
     $test = "UPDATE college_details SET college_overview='$insert_data1',
              college_courses='$insert_data2', college_facilities='$insert_data3', 
              college_image = '$file' where id = $id ";
 }

您的代码容易受到sql注入攻击。使用prepared statement更新您的数据。