我在 php 中更新产品数量时遇到问题

问题描述 投票:0回答:0

当我按下“加号”按钮时,我在更新产品数量时遇到问题,数量没有正确更新。当我有 1 个产品时它工作正常但是当我有 2 个或更多时,它没有更新并返回到初始值。 我有 updateQuantity 可以更新正常工作的产品。 请指导我如何解决这些问题。 我的 cart.php 代码:

<?php
ob_start(); // Start output buffering
session_start();
include_once $_SERVER["DOCUMENT_ROOT"] . "/database/db.php";
include 'header.php';

print_r($_SESSION);
// Initialize the cart total to 0
$total = 0;
$itemsincart = count($_SESSION['cart']);
if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {

    // Get the product IDs from the cart
    $productIds = array_keys($_SESSION['cart']);

    // Prepare the SQL statement to retrieve the product details from the database

    $stmt = $conn->prepare('SELECT * FROM products WHERE id IN (' . implode(',', $productIds) . ')');
    $stmt->execute();

    // Fetch the products from the database and store them in an array
    $result = $stmt->get_result();
    $products = array();
    while ($row = $result->fetch_assoc()) {
        $products[$row['id']] = $row;
    }
    // Insert cart data into the database for logged in users or temporary users
    if (isset($_SESSION['user_id'])) {
        $userId = $_SESSION['user_id'];
        $createdAt = date('Y-m-d H:i:s');
        echo "Count of cart items: " . count($_SESSION['cart']) . "<br>";
        echo "Looping through cart items...<br>";
        foreach ($_SESSION['cart'] as $productId => $quantity) {
            $stmt = $conn->prepare('INSERT INTO cart (product_id, quantity, user_id, created_at) VALUES (?, ?, ?, ?)');
            $stmt->bind_param('iiis', $productId, $quantity, $userId, $createdAt);
            $stmt->execute();

            if ($stmt->affected_rows > 0) {
                echo "Data inserted successfully.";
            } else {
                echo "Error inserting data.";
            }

            $stmt->close();
        }
    } else {
        $cartData = json_encode($_SESSION['cart']);
        $createdAt = date('Y-m-d H:i:s');
        $stmt = $conn->prepare('INSERT INTO temporary_carts (cart_data, created_at) VALUES (?, ?)');
        $stmt->bind_param('ss', $cartData, $createdAt);
        $stmt->execute();
        if ($stmt->affected_rows > 0) {
            echo "Data inserted successfully.";
        } else {
            echo "Error inserting data.";
        }

        $stmt->close();
    }
?>


<section class="h-100 gradient-custom">
    <div class="container py-5">
        <div class="row d-flex justify-content-center my-4">
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header py-3">
                        <h5 class="mb-0"><?php echo $itemsincart ?> محصول در سبد خرید</h5>
                    </div>
                    <div class="card-body">

                        <?php
                            // Display the cart items and their details
                            foreach ($_SESSION['cart'] as $productId => $quantity) {
                                $product = $products[$productId];
                                $subtotal = $product['off_price'] > 0 ? $product['off_price'] : $product['regular_price'];
                                $subtotaled = $subtotal * $quantity;
                                $total += $subtotaled;
                            ?>
                        <!-- Single item -->
                        <div class="row">
                            <div class="col-lg-3 col-md-12 mb-4 mb-lg-0">
                                <!-- Image -->
                                <div class="bg-image hover-overlay hover-zoom ripple rounded"
                                    data-mdb-ripple-color="light">
                                    <img src="<?= $product['image'] ?>" class="w-100" alt="Blue Jeans Jacket" />
                                    <a href="#!">
                                        <div class="mask" style="background-color: rgba(251, 251, 251, 0.2)"></div>
                                    </a>
                                </div>
                                <!-- Image -->
                            </div>

                            <div class="col-lg-5 col-md-6 mb-4 mb-lg-0">
                                <!-- Data -->
                                <p><strong>
                                        <h2 class="name"><?= $product['name'] ?></h2>
                                    </strong></p>
                                <p><?= $product['excerpt'] ?></p>
                                <form action="remove_item.php" method="post">
                                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                                    <button type="submit" class="remove-item btn btn-danger btn-sm me-1 mb-2"><i
                                            class="fas fa-trash"></i></button>
                                </form>
                                <!-- Data -->
                            </div>

                            <div class="col-lg-4 col-md-6 mb-4 mb-lg-0">
                                <!-- Quantity -->
                                <div class="d-flex mb-4" style="max-width: 300px">
                                    <button class="btn btn-primary px-3 me-2"
                                        onclick="this.parentNode.querySelector('input[type=number]').stepDown()">
                                        <i class="fas fa-minus"></i>
                                    </button>

                                    <div class="form-outline">
                                        <input id="form1" min="1" max="<?= $product['quantity'] ?>" name="quantity"
                                            value="<?= $quantity ?>" type="number" class="form-control" step="1" />
                                        <label class="form-label" for="form1"></label>
                                    </div>

                                    <button class="btn btn-primary px-3 ms-2"
                                        onclick="this.parentNode.querySelector('input[type=number]').stepUp()">
                                        <i class="fas fa-plus"></i>
                                    </button>
                                </div>
                                <!-- Quantity -->

                                <!-- Price -->

                                <div class="price text-start text-md-center"><?php
                                                                                        if ($product['off_price'] == NULL) {
                                                                                            echo "<strong><span class='regular-price'>" . "&dollar;" . $product["regular_price"] . "</span></strong>";
                                                                                        } else {
                                                                                            echo "<span style= 'text-decoration: line-through;' class='del-price'>" . "&dollar;" . $product["regular_price"] . "</span>";
                                                                                            echo "<br>";
                                                                                            echo "<strong><span class='offer-price'>" . "&dollar;" . $product["off_price"] . "</span></strong>";
                                                                                        } ?>
                                </div>
                                <div class="subtotal">
                                    Subtotal: &dollar;<?= number_format($subtotaled) ?>
                                </div>
                                <span id="subtotaled"></span>
                                <!-- Price -->
                            </div>
                        </div>
                        <?php
                            }
                        } else {
                            echo "Your cart is empty.";
                        }
                        ?>

                    </div>
                    <button class="btn btn-primary px-3 ms-2" onclick="updateQuantity(<?= $product['id'] ?>, 1)">
                        به روز رسانی محصول
                    </button>
                </div>

            </div>
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header py-3">
                        <h5 class="mb-0">خلاصه خرید</h5>
                    </div>
                    <div class="card-body">
                        <ul class="list-group list-group-flush">
                            <li
                                class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0">
                                جمع محصولات
                                <span><?php echo $total ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center px-0">
                                Shipping
                                <span>Gratis</span>
                            </li>
                            <li
                                class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 mb-3">
                                <div>
                                    <strong>Total amount</strong>
                                    <strong>
                                        <p class="mb-0">(including VAT)</p>
                                    </strong>
                                </div>
                                <span><strong>$53.98</strong></span>
                            </li>
                        </ul>

                        <button type="button" class="btn btn-primary btn-lg btn-block">
                            Go to checkout
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<script>
function updateQuantity(productId) {
    var newQuantity = document.querySelector('#form1').value;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'updateQuantity.php');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            var updatedProduct = JSON.parse(xhr.responseText);
            document.querySelector('#form1').value = newQuantity;
            // Reload the page
            location.reload();
        } else {
            alert('Error updating quantity. Please try again.');
        }
    };
    xhr.send('id=' + encodeURIComponent(productId) + '&quantity=' + encodeURIComponent(newQuantity));
}
</script>
<?php
    include 'footer.php';
    ?>

我需要解决问题的帮助

javascript php html ajax
© www.soinside.com 2019 - 2024. All rights reserved.