Hi ,

Im developing a shopping cart system.There I need to check whether the customer's cart is empty/not before going to the checkout page.If the cart is empty I need to give a message .How should I do that??

Can someone tell me..Thanks in advance...:)

Dani AI

Generated

was on the right track with a session counter, but the safest, simplest approach is to validate the cart contents on the server when the order button is submitted. That guarantees you never process an empty order even if JavaScript is bypassed or the session counter gets out of sync. For : put this check in the checkout handler (the script that runs when the order form is posted).

Example server-side check that covers common cart shapes (productId => qty, item arrays with 'qty', or indexed item arrays):

session_start();

$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : array();
$totalQty = 0;

foreach ($cart as $key => $val) {
    if (is_array($val)) {
        if (isset($val['qty'])) $totalQty += (int)$val['qty'];
        elseif (isset($val['quantity'])) $totalQty += (int)$val['quantity'];
    } else {
        $totalQty += (int)$val;
    }
}

if ($totalQty <= 0) {
    $_SESSION['error'] = 'Your cart is empty. Please add items before checkout.';
    header('Location: cart.php');
    exit;
}

Show the message on the cart page (flash pattern):

session_start();
if (!empty($_SESSION['error'])) {
    echo '<p class="error">'.htmlspecialchars($_SESSION['error']).'</p>';
    unset($_SESSION['error']);
}

Notes and troubleshooting: always call session_start() before output, call exit after header('Location: ...'), and avoid maintaining a separate counter unless you reliably update it on every cart change (it can get out of sync). Client-side checks are okay for UX, but never replace this server-side validation.

Recommended Answers

All 2 Replies

When the user adds something to that chart, add 1 to a session values, if they remove something from the chart, subtract 1 from the same session values. If the session value is empty, 0 or hasn't been set then they have nothing in the shopping chart.

Seems you didn't get what I need ..:(

adding and removing is working fine..What I need is to print a message something like validation message when a customer clicks on the order button with an empty cart...How to check it n print..

If you don't mind please give me a code .Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.