You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP网店后台多图上传至数据库报错求助

Fixing Your Multi-Image Upload & PDO Insert Errors

Let's walk through what's going wrong and fix each issue with your code:

1. Root Causes of Your Errors

Let's break down the error messages first:

  • Duplicate filenames in $aMyUploads: You're using the original upload filename for every file, so if all uploaded files share the same name (like images (1).jpg), each upload overwrites the last one, leaving your array with identical entries.
  • Undefined offset: 4: Your $aMyUploads array only has 4 elements (indexes 0-3), but you're trying to access $aMyUploads[4] in the execute() call—this index doesn't exist.
  • PDO Parameter Mismatch:
    • You mixed direct string concatenation (for image paths) with PDO placeholders (for other fields), which breaks the parameter binding system.
    • Your SQL INSERT statement has an extra trailing comma after the last value, causing invalid syntax.
    • You're passing :image1 to :image4 parameters in execute() but didn't define those placeholders in your prepared statement.

2. Fixed Code with Explanations

Here's the corrected version of your code, with comments highlighting key changes:

<?php
$db_server = "localhost";
$db_username = "root";
$db_password = "";
$db_database = "meubelfabriek";

try {
    $conn = new PDO("mysql:host=$db_server;dbname=$db_database", $db_username, $db_password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if (isset($_POST['submit'])) {
        // Define allowed image types
        $allowedTypes = ['image/jpeg', 'image/jpg'];
        $aMyUploads = [];
        $uploadSuccess = true;

        // Process each uploaded file
        foreach ($_FILES as $aFile) {
            // Skip files that weren't uploaded successfully
            if ($aFile['error'] !== UPLOAD_ERR_OK) {
                $aMyUploads[] = null; // Store null if no file was uploaded
                continue;
            }

            // Validate file type
            if (!in_array($aFile['type'], $allowedTypes)) {
                $uploadSuccess = false;
                break;
            }

            // Generate a unique filename to avoid overwriting existing files
            $extension = pathinfo($aFile['name'], PATHINFO_EXTENSION);
            $uniqueFilename = uniqid('product_img_', true) . '.' . $extension;
            $newLocation = __DIR__ . '/' . $uniqueFilename; // Use absolute path for reliability

            // Move the uploaded file to its final location
            if (move_uploaded_file($aFile['tmp_name'], $newLocation)) {
                $aMyUploads[] = $uniqueFilename; // Store only the filename (or full path if your DB expects it)
            } else {
                $uploadSuccess = false;
                break;
            }
        }

        if (!$uploadSuccess) {
            echo "<script>alert('Failed to upload images! Ensure all are JPG/JPEG and try again.')</script>";
            echo "<script>setTimeout(\"self.history.back();\", 2000);</script>";
            exit;
        }

        // Prepare SQL with ALL placeholders (no string concatenation to avoid SQL injection!)
        $stmt = $conn->prepare("
            INSERT INTO `producten` 
            (naam, beschrijving, prijs, maat1, maat2, maat3, maat4, image1, image2, image3, image4) 
            VALUES (:naam, :beschrijving, :prijs, :maat1, :maat2, :maat3, :maat4, :image1, :image2, :image3, :image4)
        ");

        // Bind all parameters correctly (match placeholders to their values)
        $stmt->execute([
            ":naam" => $_POST['fname'],
            ":beschrijving" => $_POST['desc'],
            ":prijs" => $_POST['prijs'],
            ":maat1" => $_POST['maat1'],
            ":maat2" => $_POST['maat2'],
            ":maat3" => $_POST['maat3'],
            ":maat4" => $_POST['maat4'],
            ":image1" => $aMyUploads[0] ?? null, // Use null if the index doesn't exist (prevents offset errors)
            ":image2" => $aMyUploads[1] ?? null,
            ":image3" => $aMyUploads[2] ?? null,
            ":image4" => $aMyUploads[3] ?? null
        ]);

        echo "<script>alert('Product added successfully!')</script>";
        echo "<script>setTimeout(\"window.location.href = 'your-dashboard-page.php';\", 2000);</script>";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Key Changes Made:

  • Unique Filenames: Uses uniqid() to generate unique filenames, so uploaded images won't overwrite each other.
  • Consistent PDO Placeholders: All values are bound via placeholders, eliminating SQL injection risks and fixing the parameter mismatch error.
  • Robust Error Handling: Added better checks for upload errors and file type validation, with clear user feedback.
  • Array Bound Safety: Uses the null coalescing operator (?? null) to avoid "undefined offset" errors if fewer than 4 images are uploaded.
  • Fixed SQL Syntax: Removed the extra trailing comma at the end of the VALUES list to resolve invalid SQL syntax.

3. Additional Tips

  • Always use absolute paths when moving uploaded files (like __DIR__ . '/' . $uniqueFilename) to avoid path-related issues.
  • Consider adding file size validation to prevent oversized uploads from causing problems.
  • Ensure the directory where you're storing images has proper write permissions for the web server.

内容的提问来源于stack exchange,提问作者thomas444

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:52:12