Simon
Simon

Reputation: 120

Better way to upload images?

PHP

$Product_images = $_FILES['product_img'];

foreach($Product_images['name'] as $key => $value) {

   $file_name = iSQLsecure($objConnection, $value); // iSQLsecure is my own custom function
   $file_name = trim($file_name);
   $file_tmp = $Product_images['tmp_name'][$key];
   $file_size = $Product_images['size'][$key];

   $file_ext = explode('.', $file_name);
   $file_ext = strtolower(end($file_ext));

   $file_trim_name = rtrim($file_name, ".".$file_ext);
   $file_name_new = uniqid($file_trim_name . "-", true) . '.' . $file_ext;

   $file_destination = 'img/products/' . $file_name_new;
   $image_alt = str_replace("img/products/", "", $file_destination);

   move_uploaded_file($file_tmp, "../" . $file_destination);

   $query_images = "INSERT INTO images (image_path, image_alt, fk_product_id)

   VALUES

   ('{$file_destination}', '{$image_alt}', '{$new_id}')";
   $objConnection->query($query_images) or die($objConnection->error);

}

This works, but in my opinion, I should not execute $query_images more than one time. There must be a way where I can loop through all the images I upload, but only execute $query_images once?

Upvotes: 1

Views: 25

Answers (1)

smozgur
smozgur

Reputation: 1812

Yes, there is. Use an array to add each insert value set and create single query string after the loop then execute it once.

$Product_images = $_FILES['product_img'];

$sql_insert = array();

foreach($Product_images['name'] as $key => $value) {

    // ... Previous code until $query_images = ...

    $sql_insert[] = "('{$file_destination}', '{$image_alt}', '{$new_id}')";
}

$query_images = "INSERT INTO images (image_path, image_alt, fk_product_id) 
                 VALUES " . implode(',', $sql_insert);
$objConnection->query($query_images) or die($objConnection->error);

Upvotes: 1

Related Questions