How to update my cart database on click of plus minus button in cart on ecommerce website with session_id()

Soo I want to be able to update my cart table in mysql database, when you click plus minus button in the cart of my ecommerce website. I want to be able to do this with session_id(), so no login and no cookies. Is this possible?

I tried this:

I also have a page called add_to_cart.php in which i set session_id() and update quantity everytime someone clicks on “add to cart”

<body>
    <h1>Your Cart</h1>
    <div class="cart-container" id="cart-container">
    <div class="cart">
        <?php while ($row = $result->fetch_assoc()): ?>
            <div class="cart-item" id="cart-item" data-product-id=<?php echo $row['product_id'];?>>
                <h2><?php echo $row['productname']; ?></h2>
                <img id="img" style="border-radius:20px;width:150px" src="data:image/jpg;charset=utf;base64, <?php echo base64_encode($row["productimage"]); ?>"/>
                <p>Price: $<?php echo $row['price']; ?></p>
                <div class="quantity-selector"><p>Quantity:</p>
        <button class="minus-btn" onclick="decrement(this)">-</button>
        <input type="number" id="quantity" class="quantity" value="1" min="1">
        <button class="plus-btn" onclick="increment(this)">+</button>
    </div>
                <p>Quantity: <?php echo $row['quantity']; ?></p>
                <span class="quantity">1</span>
                <p>Subtotal: $<?php echo $row['price'] * $row['quantity']; ?></p>
                
            </div>
 
        <?php endwhile; ?>
    </div>
        </div>

    <script>
var item= document.getElementsByClassName("cart-item");

function increment(element) {
    //var quantityInput = document.getElementById('quantity');
    let quantityInput = element.closest("div.cart-item").querySelector(".quantity");
    var productId = element.closest("div.cart-item").getAttribute('data-product-id');
    var currentValue = parseInt(quantityInput.value);
    //var quantitySpan = element.closest("div.cart-item").querySelector('.quantity');
    quantityInput.value = currentValue + 1;
    //var newQuantity = parseInt(quantitySpan.innerText) + 1;
    //updateQuantity(element.closest("div.cart-item").dataset.itemId, quantityInput.value);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'update_cart.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // Update the quantity in the UI
            //quantityInput.innerText = quantityInput.value;
            quantityInput.innerText = quantityInput.value;
        }
    };
    xhr.send('product_id=' + productId + '&quantity=' + quantityInput.value);
}

function decrement(element) {
    //var quantityInput = document.getElementById('quantity');
    let quantityInput = element.closest("div.cart-item").querySelector(".quantity");
    var productId = element.closest("div.cart-item").getAttribute('data-product-id');
    var currentValue = parseInt(quantityInput.value);
    if (currentValue > 1) {
        quantityInput.value = currentValue - 1;
    }
    
    //updateQuantity(element.closest("div.cart-item").dataset.itemId, quantityInput.value);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'update_cart.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // Update the quantity in the UI
            quantityInput.innerText = quantityInput.value;
        }
    };
    xhr.send('product_id=' + productId + '&quantity=' + quantityInput.value);
}

and this is my 'update_cart.php' file:

<?php
session_start();
if (!isset($_SESSION['user_session'])) {
    // Generate a new session id if not already set
    $_SESSION['user_session'] = session_id();
}

$session_id = $_SESSION['user_session'];
$product_id = $_POST['product_id'];
$new_quantity = $_POST['quantity'];

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "luciavioleta";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Update quantity in the database
$sql = "UPDATE cart SET quantity = ? WHERE user_session = ? AND product_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("isi", $new_quantity, $session_id, $product_id);

if ($stmt->execute()) {
    echo "Quantity updated successfully";
} else {
    echo "Error updating quantity: " . $conn->error;
}

$stmt->close();
$conn->close();

?>

New contributor

Luzzi98 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật