Dr3am3rz
Dr3am3rz

Reputation: 563

Validating multiple file input mysql query

My scenario is like this:

<input type="file" name="image[]" />
<input type="file" name="image[]" />
<input type="file" name="image[]" />
<input type="file" name="image[]" />

My database field table is:

ID = 1
image1 = image1.jpg
image2 = image2.jpg
image3 = image3.jpg
image4 = image4.jpg

Let's say the row id = 1 has already had values inserted previously and if the user wants to update image1 and image 4 so they will browse and select their desired image file and they leave the image2 and image3 blank.

Here's the concept after executing mysql query:

ID = 1
image1 = newimage1.jpg
image2 = image2.jpg
image3 = image3.jpg
image4 = newimage4.jpg

How do I do the validating query?

Currently my code is like this and I have no idea how to continue from here as I'm still new to PHP/mysql.

foreach ($_FILES['product_image']['name'] as $key => $value) {
if(!empty($value)) {
                `$upt=mysql_query("update products_list set` `image1='$pic1',image2='$pic2',image3='$pic3',image4='$pic4' where id='$id'");`
}
}

Hope this is clear to you guys. Thanks in advance. =)

Upvotes: 0

Views: 268

Answers (2)

Cyclonecode
Cyclonecode

Reputation: 30061

You could use a counter to update the correct field:

 foreach ($_FILES['product_image']['name'] as $key => $value) {
   if(!empty($value)) {
        // field names starts from 1
        $field = 'image'.($key+1);
        mysql_query("UPDATE product_list ".
                    "SET $field = '$value' ".
                    "WHERE id = $id");
   }
 }

Of course, this would mean that you would have to update the same record upto four times depending on what is sent from your form. Also, you should escape the user input using something like mysql_escape_string().

Upvotes: 1

maček
maček

Reputation: 77778

I think you'd be better off having product_images table. This way a product could have 1 or many images. Your form could stay the same, but you'd just associate the products.id with each each record in your new images table.

When adding a new product, you will create the product, then insert an image record for each image they uploaded in the form.

When editing a product, you could delete photos, or add new ones with ease.

// remove an image
mysql_query("delete from product_images where product_id=$pid and id=$iid");

// add a new image
mysql_query("insert into product_images (product_id, image) values ($pid, '$filename')");

Note: these queries shouldn't be used directly. Make sure that you're taking proper precaution to prevent against SQL injection.

Upvotes: 0

Related Questions