You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP+MySQL多图片商品添加与查询功能技术咨询

Hey there! Since you're new to PHP and MySQL, let's walk through exactly how to add a product with multiple images and then display that product's details later. I'll break it down into simple, actionable steps so you can follow along easily.

1. Adding a Product with Multiple Images via Form

First, we need two core parts: an HTML form to collect product data and images, and a PHP script to process that data and save it to your database.

1.1 Create the HTML Upload Form

This form needs to support file uploads, so we'll add enctype="multipart/form-data" to the form tag. We'll include fields for name, quantity, description, and a multi-file input for images.

<form method="POST" action="add_product.php" enctype="multipart/form-data">
    <div style="margin: 10px 0;">
        <label>Product Name:</label>
        <input type="text" name="name" required style="margin-left: 5px;">
    </div>
    <div style="margin: 10px 0;">
        <label>Quantity:</label>
        <input type="number" name="quantity" min="0" required style="margin-left: 10px;">
    </div>
    <div style="margin: 10px 0;">
        <label>Description:</label>
        <textarea name="description" rows="4" required style="display: block; margin-top: 5px;"></textarea>
    </div>
    <div style="margin: 10px 0;">
        <label>Product Images (select multiple):</label>
        <input type="file" name="product_images[]" multiple accept="image/*" required style="display: block; margin-top: 5px;">
    </div>
    <button type="submit">Add Product</button>
</form>

1.2 PHP Backend to Handle Submission

Save this as add_product.php. This script will connect to your database, insert the product details first, then handle each image upload and link it to the product via the productId field. We'll use a database transaction to ensure if something goes wrong (like an upload fails), we don't end up with a product without images.

<?php
// Connect to your database (replace with your credentials)
$conn = new mysqli('localhost', 'your_username', 'your_password', 'your_database');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Only run when the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize input to prevent SQL injection
    $name = $conn->real_escape_string($_POST['name']);
    $quantity = (int)$_POST['quantity'];
    $description = $conn->real_escape_string($_POST['description']);

    // Start a database transaction
    $conn->begin_transaction();

    try {
        // Insert product into the product table
        $productQuery = "INSERT INTO product (name, quantity, description) VALUES ('$name', $quantity, '$description')";
        if (!$conn->query($productQuery)) {
            throw new Exception("Failed to add product: " . $conn->error);
        }
        // Get the ID of the newly added product
        $productId = $conn->insert_id;

        // Set up the upload directory (create it if it doesn't exist)
        $uploadDir = 'uploads/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // Loop through each uploaded image
        foreach ($_FILES['product_images']['tmp_name'] as $key => $tempFilePath) {
            $originalFileName = $_FILES['product_images']['name'][$key];
            $fileSize = $_FILES['product_images']['size'][$key];
            $fileType = $_FILES['product_images']['type'][$key];

            // Validate the image file
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (!in_array($fileType, $allowedTypes)) {
                throw new Exception("File '$originalFileName' is not a valid image (only JPG, PNG, GIF allowed).");
            }
            if ($fileSize > 5 * 1024 * 1024) { // Limit to 5MB per image
                throw new Exception("File '$originalFileName' is too large (max 5MB).");
            }

            // Rename the file to avoid duplicates
            $uniqueFileName = uniqid() . '-' . basename($originalFileName);
            $finalFilePath = $uploadDir . $uniqueFileName;

            // Move the uploaded file to our uploads folder
            if (!move_uploaded_file($tempFilePath, $finalFilePath)) {
                throw new Exception("Failed to upload '$originalFileName'.");
            }

            // Insert the image path into the image table, linked to the product
            $imageQuery = "INSERT INTO image (productId, imagepath) VALUES ($productId, '$finalFilePath')";
            if (!$conn->query($imageQuery)) {
                throw new Exception("Failed to save image record for '$originalFileName': " . $conn->error);
            }
        }

        // If everything worked, commit the transaction
        $conn->commit();
        echo "<p>Product added successfully! <a href='product_details.php?id=$productId'>View product</a></p>";
    } catch (Exception $e) {
        // If something went wrong, roll back the transaction
        $conn->rollback();
        echo "<p>Error: " . $e->getMessage() . "</p>";
    }

    $conn->close();
}
?>
2. Displaying Product Details with Multiple Images

Now let's create a page to show the product's info and all its images. Save this as product_details.php.

2.1 PHP to Fetch Product and Images

This script will get the product ID from the URL (like product_details.php?id=1), fetch the product details, then fetch all images linked to that product.

<?php
// Connect to database
$conn = new mysqli('localhost', 'your_username', 'your_password', 'your_database');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Make sure we have a valid product ID from the URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid product ID.");
}
$productId = (int)$_GET['id'];

// Fetch product details
$productQuery = "SELECT * FROM product WHERE id = $productId";
$productResult = $conn->query($productQuery);
$product = $productResult->fetch_assoc();

if (!$product) {
    die("Product not found.");
}

// Fetch all images for this product
$imagesQuery = "SELECT * FROM image WHERE productId = $productId";
$imagesResult = $conn->query($imagesQuery);
$productImages = [];
while ($imageRow = $imagesResult->fetch_assoc()) {
    $productImages[] = $imageRow;
}

$conn->close();
?>

2.2 HTML to Display the Content

Add this below the PHP code in product_details.php to render the product info and images:

<!DOCTYPE html>
<html>
<head>
    <title><?php echo htmlspecialchars($product['name']); ?></title>
    <style>
        .product-container { max-width: 800px; margin: 20px auto; padding: 0 20px; }
        .product-images { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 15px; }
        .product-images img { max-width: 300px; height: auto; border-radius: 4px; }
    </style>
</head>
<body>
    <div class="product-container">
        <h1><?php echo htmlspecialchars($product['name']); ?></h1>
        <p><strong>Quantity in Stock:</strong> <?php echo $product['quantity']; ?></p>
        <p><strong>Description:</strong><br><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>

        <h2>Product Images</h2>
        <div class="product-images">
            <?php if (empty($productImages)): ?>
                <p>No images available for this product.</p>
            <?php else: ?>
                <?php foreach ($productImages as $image): ?>
                    <img src="<?php echo htmlspecialchars($image['imagepath']); ?>" alt="Product image">
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
Important Tips for Beginners
  • Security First: The code above uses basic sanitization, but for production, use prepared statements (mysqli or PDO) to avoid SQL injection entirely. Also, don't use 0777 for folder permissions in production—adjust to the minimal required permissions for your server.
  • Error Handling: In a live site, don't show raw error messages to users. Instead, log errors to a file and show a friendly "Something went wrong" message.
  • Validation: Add more checks if needed, like making sure the product name isn't too long, or quantity is a positive number.

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

火山引擎 最新活动