Almeister9
Almeister9

Reputation: 161

php upload file on Edit form, prevent UPDATE if no file

I have a form to Edit existing values in a MySQL table. One of the fields stores the filename of an image, (another stores the folder location of the image) The file has an upload field to upload another image and replace the image name in the original image name field.

This works fine if I choose a file, to replace the existing image. If I don't choose to replace the image, the field is UPDATE with the empty data.

Basically I am trying to only do the UPDATE sql query if there is an image chosen and uploaded.

I am using this code:

if(!empty($_FILES['file_slick']))
{
$slick = $_FILES['file_slick']['name'];
copy($_FILES['file_slick']['tmp_name'],'../images/product/'.$folder.'/'.$slick); 
$sql_slick = "UPDATE tbl_product SET prod_slick = '".$slick."' WHERE prod_id = '".$prodid."'";
mysql_query($sql_slick);
}

I have tried if(!empty($_POST['file_slick'])) but neither works. If a file is chosen and uploaded, it is moved to the correct folder and the image filename is updated into the field. If an image is not chosen, empty data is updated into the image filename field.

I have looked around the internet (and mostly here) and from what I can see, my check to prevent empty data should work.

Can anyone see anything wrong here?

Upvotes: 1

Views: 11503

Answers (3)

Samuel
Samuel

Reputation: 1

In your script to handle the database query, just before the query, set the query placeholders for your file path or whatever reference to the image or file that was uploaded to a variable sourced from the database.

For eg. in a project I was doing, it had to display the file path of the already stored file. So i pulled that from the database and kept it somewhere so that if filepath before the query is empty() then set it to the former values.

I've not spotted any downside but I'm sure there might be small catch since im rewritting the database with what was there already if no new submission was made, everytime I make changes.

My script was like this

$final_size = size_calc( $upload['size'] );
$file_path = addslashes(UPLOAD_DIR . $name);

if ( empty($file_path) ) $file_path = addslashes( $post['file_path'] );
    if ( empty($final_size) ) $final_size = $post['file_size'];
//Perform query
$query = "UPDATE posts SET post_title = '{$post_title}', visible =     {$visible}, post_content = '{$post_content}', post_cat_id =     '{$post_cat_id}',file_path = 
    '{$file_path}', file_size = '{$final_size}' WHERE id = {$post_id} LIMIT 1";
    $result = mysqli_query( $link , $query );

Upvotes: 0

5z- -
5z- -

Reputation: 161

because $_FILES['file_slick'] is a multidimensional array,so the function empty return true,you can use $_FILES['file_slick']['error'] == 0 to check the image

Upvotes: 0

qisho
qisho

Reputation: 364

try if(!empty($_FILES['file_slick']['name']))

Upvotes: 4

Related Questions