【问题标题】:Upload multiple images with foreach使用 foreach 上传多张图片
【发布时间】:2015-02-17 16:41:32
【问题描述】:

我在互联网上搜索了几天,但我无法弄清楚。

我有这个代码

    foreach($_FILES['image']['name'] as $key => $value)
    {
        $name = $_FILES['image']['name'][$key];
    }

我在 phpmyadmin 中有一个名为 img 的表,其中有两行 (url1) 和 (url2.

例如,我提交 'pic1,jpg' 和 'pic2.jpg' 并且我想将 'pic1.jpg' 放在 url1 行中 和 'pic2.jpg' 在 url2 行中

我该怎么做,因为我无法通过 foreach 循环访问图像的名称。

例如变量 $name 中有这两张图片,我将如何回显第二张图片? 没有给我看这两张照片。

请帮帮我,我已经挣扎了好几天了,还留了胡子。

【问题讨论】:

  • 简单:您不将图像存储在数据库中。很少有用例可以证明这一点,而且数据库内图像的痛苦远远超过了这些用例获得的微小优势。
  • 我将路径存储在数据库中...

标签: php database mysqli upload


【解决方案1】:

如果您只上传 2 张图片:

$images = $_FILES['images'];

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

     $file_name[$key] = $value;
     $file_tmp = $images['tmp_name'][$key];

     $file_ext = explode('.', $file_name); // images.jpg becomes images jpg
     $file_ext = strtolower(end($file_ext)); // We make the extension (jpg, gif etc.)
     // lowercase and separate it with "end" from images, which leaves us the extension

     $file_trim_name = rtrim($file_name, ".".$file_ext); // We remove the extension (.jpg)
     // from the image name

     $file_name_new = uniqid($file_trim_name . "-", true) . '.' . $file_ext; // Create a
     // "uniqid" (if you do not want to overwrite other images). We take the image name
     // and separate name and id by "-" and add the extension afterwards: $file_name_new = images-20302.jpg

     $file_destination = 'image/folder/location' . $file_name_new; // Choose file location

     move_uploaded_file($file_tmp, $file_destination); // Here we move images to their
     // location with the function "move_uploaded_file"

}

$url1 = $file_destination[0]; // Selecting first image
$url2 = $file_destination[1]; // Selecting second image

$query_images = "INSERT INTO images (url1, url2)

VALUES

('{$url1}', '{$url2}'";

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2017-04-08
    • 2014-03-19
    • 2011-12-10
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多