Search code examples
phpmysqlfile-uploadis-empty

php if empty skip action


I have a form with field

<input type="file" name="file" size="100" value="">

if this field is empty I want to skip trying to upload the image (because there isnt one) and only update any information that has changed. If an image is present upload it and update the mysql database.

This code was only working if a new image was being uploaded. Added the if(!empty but now the wrong file type code is popping when the form field is left blank?

// connect to datebase
require "master.db.php";

if(!empty($_FILES['file']))
    {
      if ( file types )
          {
           // upload the file
          }
       else
          {
           // wrong file type
                 die;
           }
     }

else {
    // update other data in mysql database
    $sql="UPDATE `characters` SET test='test' WHERE ID='$id'";
    $result=mysql_query($sql);

    // if successfully updated mysql.
       if($result){
          echo "<b>Update successful</b> <br />";
          echo "<a href='../test.html'>View result</a>";
          touch('../master.html');
          clearstatcache();
          }

        else {
             echo "Whoops: " . mysql_error(); ;
              }
    mysql_close();
    }

Solution

  • use this

    if(!$_FILES['file']){ 
         echo "file is empty" 
    }
    

    instead of

    if(empty($_POST['file']))
    

    finally

        if(!empty($_FILES['file'])){ 
         //file has something
        }
       else{
         //either file is empty or filed is not set
       }