Not changing database value for file upload if blank?

I’m attempting to do an file upload form for when you update the system but when you click the submit button, if you have not added any files then it wont change the database row to a blank and just keep the previous value in it.

Currently i have all the file uploads working but if you dont add any files then it just changes the database rows to blank so does anyone know a way how i can do this without having to do separate forms for each file upload field.

My code

<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
require_once('../system/config-admin.php');

/*if(!empty($_POST['updatedata']))
{*/


if(!empty($_FILES['previewimgfile']['name'])){
if(isset($_FILES['previewimgfile'])){
  $image_name = $_FILES['previewimgfile']['name'];
  $image_name = preg_replace("/[^a-zA-Z0-9áéíóúüñÁÉÍÓÚÜÑ.\']/", "", $image_name);
  $tmp_name   = $_FILES['previewimgfile']['tmp_name'];
  $image_type = $_FILES['previewimgfile']['type'];
  $image_size = $_FILES['previewimgfile']['size'];
  $allowed_image = array('image/png', 'image/PNG', 'image/jpeg', 'image/JPEG');
  if(!in_array($image_type, $allowed_image)){
    echo '<span class="text-danger">Please select a jpg/png for preview img!</span>';
    die();
  }
  else
  {
      if($image_size > 5767168){
          echo'file too big';
          die();
      }
      else{
    $new_image_name = time().$image_name;
    move_uploaded_file($tmp_name, '../system/assets/uploads/products/'.$new_image_name.'');
    }
  }
}
}
if(!empty($_FILES['iconimgfile']['name'])){
if(isset($_FILES['iconimgfile'])){
  $aimage_name = $_FILES['iconimgfile']['name'];
  $aimage_name = preg_replace("/[^a-zA-Z0-9áéíóúüñÁÉÍÓÚÜÑ.\']/", "", $aimage_name);
  $tmp_name   = $_FILES['iconimgfile']['tmp_name'];
  $aimage_type = $_FILES['iconimgfile']['type'];
  $aimage_size = $_FILES['iconimgfile']['size'];
  $aallowed_image = array('image/png', 'image/PNG', 'image/jpg', 'image/JPG');
  if(!in_array($aimage_type, $aallowed_image)){
    echo '<span class="text-danger">Please select a jpg/png for icon img!</span>';
    die();
  }
  else
  {
      if($aimage_size > 5767168){
          echo'file too big';
          die();
      }
      else{
    $new_image_name1 = time().$aimage_name;
    move_uploaded_file($tmp_name, '../system/assets/uploads/products/'.$new_image_name1.'');
    }
  }
}
}
if(!empty($_FILES['mainfile']['name'])){
if(isset($_FILES['mainfile'])){
  $name = $_FILES['mainfile']['name'];
  $name = preg_replace("/[^a-zA-Z0-9áéíóúüñÁÉÍÓÚÜÑ.\']/", "", $name);
  $tmp_name   = $_FILES['mainfile']['tmp_name'];
  $file_size = $_FILES['mainfile']['size'];
if($file_size < 1){
    echo 'No file selcted try again!';
    die();
}
  $file_type = pathinfo($name);
  $file_type = $file_type['extension'];
  $allowed_file = array('zip','jpg');
  if(!in_array($file_type, $allowed_file)){
    echo '<span class="text-danger">Please select a .zip file for the main file</span>';
  }
  else
  {
    $new_file_name = time().$name;
    move_uploaded_file(''.$tmp_name.'', '../system/assets/uploads/product-files/'.$new_file_name.'');
}
  }
}

/*}else{
  echo '<span class="text-danger">You need to add atleast one file!</span>';
  die();
}*/

$id = $_POST['id'];

$sql_upload = $DB_con->prepare("UPDATE dsptesty_products SET icon_img=:icon_img, preview_img=:preview_img, file=:file WHERE id=:id");

$sql_upload->bindparam(":icon_img",$new_image_name1);
$sql_upload->bindparam(":preview_img",$new_image_name);
$sql_upload->bindparam(":file",$new_file_name);
$sql_upload->bindparam(":id",$id);

if($sql_upload->execute()){
echo '<span class="text-success">Product Files Updated!</span>';
}
else{
echo "Error: " . $sql_upload->error;
}

}
else {
  header('location: ../index.php');
}
?>

My File Upload Form Code

    <div class="my-3 p-3 bg-white rounded box-shadow">
                            
                            
                            <form id="upload1" class="form-horizontal">

                    <div class="form-group"> <label>Main File (.ZIP):</label> 
                                   <div class="input-group">
  <div class="custom-file">
    <input type="file" name="mainfile" class="custom-file-input" id="inputGroupFile04">
    <label class="custom-file-label" for="inputGroupFile04">Choose File</label>
  </div>
</div>
                    </div>

                    <div class="form-group"> <label>Icon Image File (.PNG,.JPG):</label> 
                                   <div class="input-group">
  <div class="custom-file">
    <input type="file" name="iconimgfile" class="custom-file-input" id="inputGroupFile04">
    <label class="custom-file-label" for="inputGroupFile04">Choose File</label>
  </div>
</div>
                    </div>
                    
                                        <div class="form-group"> <label>Preview Image File (.PNG,.JPG):</label> 
                                   <div class="input-group">
  <div class="custom-file">
    <input type="file" name="previewimgfile" class="custom-file-input" id="inputGroupFile04">
    <label class="custom-file-label" for="inputGroupFile04">Choose File</label>
  </div>
</div>
                    </div>

<hr>
  <input class="form-control" type="hidden" name="id" value="<?php echo $productDetails['id'];?>"> 
<button type="submit" id="btn" class="btn btn-primary w-100">Update Files</button>
<script type="text/javascript">
  $("#upload1").on("submit",(function(e) {
    e.preventDefault();
    $.ajax({
          url: "<?php echo $setting['website_url'];?>/admin/ajax-update-files.php",
      type: "POST",
      data:  new FormData(this),
      contentType: false,
          cache: false,
      processData:false,
      beforeSend: function() 
        {
            $("#res1").html('Updating..Please wait!');
        },  
        success: function(response)
        {
            $("#res1").html(response);
        }        
     });
  }));
</script>
<div id="res1"></div>
</form> </div>

Thanks very much for help in advance!

just put the update where the condition is, or check the condition a second time where the update is.

please can you show me an example

Thanks

how did you manage to write the code above? you already have the condition there: if(isset($_FILES['previewimgfile'])){

yes exactly so i don’t know why it is not already working but what it does is even if i don’t change/upload a new file it will change the database value to a blank and i can’t see what I’m doing wrong with my current conditions and i thought the !empty would of fixed it but it didn’t!

All of the file uploads are within nested if() clauses. The database update is outside of all of those clauses, so it will execute regardless of whether any of the files were specified and/or successfully uploaded.

You could set a flag each time you successfully upload any of the images, or you could just check which of the filenames you are setting actually has something in it by the time you get to run the query. You will need to edit the query to handle situations where there are different numbers of images uploaded.

is missed the word “wrong” / i cant see what im doing wrong.

This is my second time working with file uploads and i don’t truly understand everything but i get if/else statements because what i thought my current code would do is if the field is not empty then run the code but if it is empty then move onto the next clause and so on but its like if i only upload one, the other two variables/data in the db is gone

Yes, that’s what your query does. You supply three filenames via parameters (good to see, btw) into the query, and the values of those parameters are stuck into the database. If any of them are blank, that’s what gets put into the database, so it will overwrite what you have. The query does not decide to not do the update if any of them are blank - what if you wanted to blank them out?

Thinking about it, it might actually be easier to run three separate queries, one for each image. Surround each one with an if/then to see if there’s anything in the uploaded image file name, if there is, have your query update just that single column. That might be easier to read than trying to build up a list of column names and substitute them into the query, given that you can’t use a parameter for a column name. Something like

if (icon-filename !== "") { 
  // run the query for the icon filename
  $sql_upload = $DB_con->prepare("UPDATE dsptesty_products SET icon_img=:icon_img WHERE id=:id");
  // add parameters
  // execute query
}
if (preview-filename !== "") { 
  // for the preview
}
... and so on
1 Like

Thanks this seems to work and i see what you mean i just always thought there was a cleaner/all in one go way but thanks very much this worked! :slight_smile:

I know there are ways in the query to only update a field if it’s currently blank, but I’m not sure there’s a way to do it the other way around.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.