首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >上传图片的更好方法?

上传图片的更好方法?
EN

Stack Overflow用户
提问于 2016-06-04 11:50:31
回答 1查看 22关注 0票数 1
代码语言:javascript
复制
$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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-04 11:58:38

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

代码语言:javascript
复制
$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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37629894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档