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

PHP MySQL购物车改造:合并商品盒+带预选的联动价格下拉列表

Modified Shopping Cart System with Combined Product Box & Dynamic Price Selection

Got it, let's tackle your requirements step by step. Here's how to adjust your existing PHP/MySQL shopping cart to get the functionality you need:

First: Clean Up Redundant Database Connection

Your original PHP code had duplicate database connections—let's fix that first for cleaner code:

<?php
session_start();
// Single, consistent database connection
$connect = new mysqli("localhost", "root", "", "test");
if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}
$connect->set_charset("utf8");

// Rest of your cart logic remains the same
if(isset($_POST["add_to_cart"])) {
    if(isset($_SESSION["shopping_cart"])) {
        $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
        if(!in_array($_GET["id"], $item_array_id)) {
            $count = count($_SESSION["shopping_cart"]);
            $item_array = array(
                'item_id' => $_GET["id"],
                'item_name' => $_POST["hidden_name"],
                'item_price' => $_POST["hidden_price"],
                'item_quantity' => $_POST["quantity"]
            );
            $_SESSION["shopping_cart"][$count] = $item_array;
        } else {
            echo '<script>alert("Item Already Added")</script>';
            echo '<script>window.location="index.php"</script>';
        }
    } else {
        $item_array = array(
            'item_id' => $_GET["id"],
            'item_name' => $_POST["hidden_name"],
            'item_price' => $_POST["hidden_price"],
            'item_quantity' => $_POST["quantity"]
        );
        $_SESSION["shopping_cart"][0] = $item_array;
    }
}

if(isset($_GET["action"])) {
    if($_GET["action"] == "delete") {
        foreach($_SESSION["shopping_cart"] as $keys => $values) {
            if($values["item_id"] == $_GET["id"]) {
                unset($_SESSION["shopping_cart"][$keys]);
                echo '<script>alert("Item Removed")</script>';
                echo '<script>window.location="index.php"</script>';
            }
        }
    }
}
?>

Full Modified HTML Code (Combined Box + Dynamic Price)

This code merges all products into a single display box and adds the price-changing dropdown:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> Simple PHP Mysql Shopping Cart</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function(){
            // Handle price dropdown selection changes
            $('.price-option').change(function(){
                const $productBox = $(this).closest('.product-item');
                const selectedPrice = parseFloat($(this).find(':selected').data('price'));
                
                // Update visible price display
                $productBox.find('.product-price').text('DKK ' + selectedPrice.toFixed(2));
                // Update hidden price input to send correct value to cart
                $productBox.find('.hidden-price').val(selectedPrice.toFixed(2));
            });
        });
    </script>
</head>
<body>
<br />
<div class="container" style="width:700px;">
    <h3 align="center">LS-Net Shopping Cart</h3><br />
    <?php 
    $query = "SELECT * FROM tbl_product ORDER BY id ASC";
    $result = $connect->query($query);
    if($result->num_rows > 0) { 
    ?>
    <!-- Single combined product display box -->
    <div class="col-md-12">
        <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;">
            <div class="row">
                <?php while($row = $result->fetch_array()) { ?>
                <div class="col-md-4 product-item" align="center">
                    <form method="post" action="index.php?action=add&id=<?php echo $row["id"]; ?>">
                        <img src="<?php echo $row["image"]; ?>" class="img-responsive"/><br />
                        <h4 class="text-info"><?php echo $row["name"]; ?></h4>
                        
                        <!-- Price options dropdown (added between name and price) -->
                        <select class="form-control price-option">
                            <option value="standard" data-price="<?php echo $row["price"]; ?>">Standard</option>
                            <option value="lille_mæl" data-price="<?php echo $row["price"] * 1.1; ?>">lille mæl</option>
                            <!-- Add more price options here as needed -->
                        </select>
                        
                        <h4 class="text-danger product-price">DKK <?php echo $row["price"]; ?></h4>
                        <input type="text" name="quantity" class="form-control" value="1" />
                        <input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
                        <input type="hidden" name="hidden_price" class="hidden-price" value="<?php echo $row["price"]; ?>" />
                        <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
                    </form>
                </div>
                <?php } ?>
            </div>
        </div>
    </div>
    <?php } ?>
    <div style="clear:both"></div>
    <br />
    <h3>Order Details</h3>
    <div class="table-responsive">
        <table class="table table-bordered">
            <tr>
                <th width="40%">Item Name</th>
                <th width="10%">Quantity</th>
                <th width="20%">Price</th>
                <th width="15%">Total</th>
                <th width="5%">Action</th>
            </tr>
            <?php 
            if(!empty($_SESSION["shopping_cart"])) {
                $total = 0;
                foreach($_SESSION["shopping_cart"] as $keys => $values) {
            ?>
            <tr>
                <td><?php echo $values["item_name"]; ?></td>
                <td><?php echo $values["item_quantity"]; ?></td>
                <td>DKK <?php echo $values["item_price"]; ?></td>
                <td>DKK <?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td>
                <td><a href="index.php?action=delete&id=<?php echo $values["item_id"]; ?>"><span class="text-danger">Remove</span></a></td>
            </tr>
            <?php 
                    $total = $total + ($values["item_quantity"] * $values["item_price"]);
                }
            ?>
            <tr>
                <td colspan="3" align="right">Total</td>
                <td align="right">DKK <?php echo number_format($total, 2); ?></td>
                <td></td>
            </tr>
            <?php } ?>
        </table>
    </div>
</div>
<br />
</body>
</html>

Key Changes Explained

  1. Combined Product Box: All products are now wrapped in a single outer container with a shared border, replacing the individual per-product boxes. Each product still uses col-md-4 for a responsive 3-column layout inside the box.
  2. Dynamic Price Dropdown:
    • Added a <select> element between the product name and price display. Each option has a data-price attribute storing the corresponding price.
    • jQuery listens for dropdown changes: when a user selects an option (like "lille mæl"), it updates both the visible price text and the hidden hidden_price input—so the correct price is sent to the cart when adding the item.
  3. Cleaner Database Queries: Switched to object-oriented MySQLi methods (like $connect->query()) to match the initial connection setup.

Quick Notes

  • Adjust the price values in the dropdown options to match your actual pricing rules (you could also pull these from a database table if you have multiple price tiers per product).
  • The product-item class ensures we only update the price for the selected product, not all products at once.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:50:03