更好的上传图片的方式?

时间:2016-06-04 11:50:32

标签: php arrays database file-upload mysqli

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);

}

这有效,但在我看来,我不应该多次执行$query_images。必须有一种方法可以遍历我上传的所有图像,但只能执行$query_images一次?

1 个答案:

答案 0 :(得分:1)

是的,有。使用数组添加每个插入值集,并在循环后创建单个查询字符串,然后执行一次。

$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);