atul tyagi
atul tyagi

Reputation: 41

Submit a form with file input left blank

I am submitting a form where I am updating the state id, city name and city image.

When I only update the image, it works. When I update state id and city name and want my old image to remain the same, the photo field become blank in the database.

My PHP code is like this:

 <?php 

if(isset($_POST) && $_POST['submit'] == "Update")
{
        extract($_POST);
        if($_FILES['photo'])
        {
        $cityimg = upload_file($_FILES['photo'],'cityimg/','image','N','true','thumb/', 100, 100);
        $sql = "UPDATE city SET mcid = '$mcid', city_name = '$city_name', photo = '$cityimg' WHERE cid = '$cid'";
        }
        else
        {
        $sql = "UPDATE city SET mcid = '$mcid', city_name = '$city_name' WHERE cid = '$cid'";
        }
        $result = mysql_query($sql);
        if($result)
        {
            $msg = "City Updated Successfully.";
        }
}

?>

I think that my loop is having some problem.

Upvotes: 0

Views: 511

Answers (1)

rayfranco
rayfranco

Reputation: 3690

You should test if a file was uploaded in a different way. For example, this will make sure that no error occurred during the file upload (and if there was any) :

if($_FILES['photo']['error'] == UPLOAD_ERR_OK){
    // A file was uploaded and there is no error
}

If you only want to test if no file was selected, you could use UPLOAD_ERR_NO_FILE.

More info on file upload error messages

This should work for you :

<?php 

if(isset($_POST) && $_POST['submit'] == "Update")
{
        extract($_POST);

        // If image was uploaded
        if($_FILES['logo']['error'] == UPLOAD_ERR_OK)
        {
            $cityimg = upload_file($_FILES['photo'],'cityimg/','image','N','true','thumb/', 100, 100);
            $sql = "UPDATE city SET mcid = '$mcid', city_name = '$city_name', photo = '$cityimg' WHERE cid = '$cid'";
        }

        // If no image was uploaded
        else
        {
            $sql = "UPDATE city SET mcid = '$mcid', city_name = '$city_name' WHERE cid = '$cid'";
        }
        $result = mysql_query($sql);
        if($result)
        {
            $msg = "City Updated Successfully.";
        }
}

Check this post for more details

Upvotes: 1

Related Questions