php - 上传图片的更好方法?

标签 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 吗?

最佳答案

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

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

关于php - 上传图片的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37629894/

相关文章:

php - 如何跳过数组的日期并将日期增加+1?

c++ - 如何在 C++ 中将 .txt 文件复制到 char 数组

Mysql LIMIT 使用 MATCH AGAINST

php - 分析 API : automatic authentification

php - 我可以使用准备好的语句启用/禁用部分查询吗?

javascript - 如何将错误响应从 php 发送到 jQuery Ajax post 请求

mysql 左连接问题

php - 使用 PHP 按姓氏对 CSV 文件进行排序

Java : CSV reading with ArrayList of List of Integer

sql - 在 SQL Server 2012 中,INSERT INTO 随着时间的推移变得更慢