首页 > 解决方案 > PHP多张图片只上传第一张图片

问题描述

我正在尝试从一个输入字段“上传”多个图像。我将它们移动到我的“上传”目录并将它们的路径保存到我的数据库中。移动部分工作正常,但由于某种原因,它只存储第一个选定图像的路径,并给出警告消息:

mysqli_stmt::bind_param(): Couldn't fetch mysqli_stmt in

编码:

    $filesTempName = $_FILES['images']['tmp_name'];
    $counted = count($filesTempName);
    $maxSize = 2100000;
    $errorMsg = "";

    if ($counted > 5) {
        $errorMsg = "Maximum 5 images!";
    } else {
        for ($i = 0; $i < $counted; $i++) {
            if (empty($filesTempName[$i])) {
                $stmt->execute();
                $stmt->close();
                $link->close();
            } else {
                $allowed_types = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
                $detectedType = exif_imagetype($filesTempName[$i]);

                if ($_FILES["images"]["size"][$i] > $maxSize) {
                    $errorMsg = "max 2mb!";
                } elseif (!in_array($detectedType, $allowed_types)) {
                    $errorMsg = "error!";
                } else {
                    $stmt->execute(); //I store other data here, it works fine.
                    $stmt->close();

                    $productid = $link->insert_id;

                    $statement = $link->prepare("INSERT INTO images(thumbnailimage, productid) VALUES(?, ?)");
                    for ($i = 0; $i < $counted; $i++) {
                        $file = $filesTempName[$i];
                        if (is_uploaded_file($file) && !empty($file)) {
                            $data = "uploads/" . time() . $_FILES["images"]["name"][$i];
                            move_uploaded_file($file, $data);
                            $statement->bind_param("si", $data, $productid);
                            $statement->execute(); // I get error for this line
                            $statement->close();
                        }
                    }
                }
            }
        }
    }

这部分抛出错误:

$statement->execute();

标签: phpmysqli

解决方案


$statement->close();从您的代码中删除。您不应该手动关闭语句或连接。也一样$link->close();


推荐阅读