DEV Community

Arya Ishaan Patrjbauli
Arya Ishaan Patrjbauli

Posted on

Cart Functions and how to do them in PHP

In the world of online shopping, one of the most essential features of any e-commerce site is the shopping cart. A well-built cart system not only improves the user experience but also drives conversions. In PHP, creating and managing cart functionality is both flexible and efficient, allowing you to handle complex cart operations such as adding items, updating quantities, and removing products seamlessly. In this blog, we’ll explore how to implement basic shopping cart functions in PHP, from creating the cart session to calculating totals, so you can build a dynamic and user-friendly cart system for your online store.

lets start with the basic functions!

function addToCart($conn, $productId)
{
    $stmt = $conn->prepare("SELECT * FROM products WHERE id = :id");
    $stmt->bindParam(':id', $productId);
    $stmt->execute();
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($product) {
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = array();
        }

        if (isset($_SESSION['cart'][$productId])) {
            $_SESSION['cart'][$productId]['quantity']++;
        } else {
            $_SESSION['cart'][$productId] = array(
                'id' => $product['id'],
                'name' => $product['name'],
                'price' => $product['price'],
                'quantity' => 1
            );
        }
        return true;
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode
  1. addToCart($conn, $productId) This function is responsible for adding products to the shopping cart. It performs the following steps:

Fetch Product Details: It uses a prepared statement to fetch the product details from the products table by its id. This ensures that the product exists in the database.

Check if Cart Exists: If the cart ($_SESSION['cart']) is not initialized yet, the function creates an empty cart (an empty array).

Check if Product Already in Cart: If the product is already in the cart, it increments the product's quantity by 1.

Add New Product to Cart: If the product is not already in the cart, it adds the product with a quantity of 1. The product's ID, name, price, and quantity are stored in the cart.

The function returns true if the product is successfully added, otherwise false if the product is not found.

function removeFromCart($productId)
{
    if (isset($_SESSION['cart'][$productId])) {
        unset($_SESSION['cart'][$productId]);
        return true;
    }
    return false;
}

function updateCartQuantity($productId, $quantity)
{
    if (isset($_SESSION['cart'][$productId])) {
        $_SESSION['cart'][$productId]['quantity'] = max(1, (int)$quantity);
        return true;
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode
  1. removeFromCart($productId) This function handles the removal of a product from the cart:

Check if Product Exists in Cart: It checks if the product with the given productId exists in the cart ($_SESSION['cart']).

Remove Product: If the product is found, it is removed from the cart using unset(), which deletes the product from the session.

The function returns true if the product is removed successfully, otherwise false if the product is not in the cart.

function getCartTotal()
{
    $total = 0;
    if (isset($_SESSION['cart'])) {
        foreach ($_SESSION['cart'] as $item) {
            $total += $item['price'] * $item['quantity'];
        }
    }
    return $total;
}
Enter fullscreen mode Exit fullscreen mode

getCartTotal()
This function calculates the total price of all products in the cart:

Initialize Total: A variable $total is initialized to 0.

Sum Prices: The function loops through each item in the cart ($_SESSION['cart']). For each item, it multiplies the price by the quantity and adds the result to the $total.

The function returns the total price of all items in the cart.

  1. Adding to the Cart: The first part checks if a product ID is provided in the URL ($_GET['id']). If so, it attempts to add the product to the cart using the addToCart function. If successful, a success message is stored in the session; if the product is not found, an error message is stored. If no product ID is given, an error message indicating an invalid product ID is stored. After handling the request, the user is redirected back to the previous page using header("Location: " . $_SERVER['HTTP_REFERER']);.
<?php
require_once 'incall.php';

if (isset($_GET['id'])) {
    $product_id = $_GET['id'];

    if (addToCart($conn, $product_id)) {
        $_SESSION['success_message'] = "Product added to cart successfully!";
    } else {
        $_SESSION['error_message'] = "Product not found.";
    }
} else {
    $_SESSION['error_message'] = "Invalid product ID.";
}

// Redirect back to the previous page or to the cart page
header("Location: " . $_SERVER['HTTP_REFERER']);
exit();

Enter fullscreen mode Exit fullscreen mode

Cart Page:
The cart page allows users to remove items or update quantities.
If a remove parameter is set in the URL, it calls removeFromCart to delete the specified item and shows a success message if the operation is successful.
When the form is submitted via POST, it updates the product quantity using the updateCartQuantity function, displaying an appropriate success message.

cart.php

<?php
require_once 'incall.php';


// Handle cart operations
if (isset($_GET['remove'])) {
    if (removeFromCart($_GET['remove'])) {
        $_SESSION['success_message'] = "Item removed from cart.";
    }
    header("Location: cart.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'], $_POST['quantity'])) {
    if (updateCartQuantity($_POST['id'], $_POST['quantity'])) {
        $_SESSION['success_message'] = "Cart updated successfully!";
    }
    header("Location: cart.php");
    exit();
}

// Display messages
foreach (['success_message' => 'green', 'error_message' => 'red'] as $key => $color) {
    if (isset($_SESSION[$key])) {
        echo "<div style='color: $color;'>" . htmlspecialchars($_SESSION[$key]) . "</div>";
        unset($_SESSION[$key]);
    }
}

if (!empty($_SESSION['cart'])): ?>
    <table>
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Subtotal</th>
            <th>Action</th>
        </tr>
        <?php foreach ($_SESSION['cart'] as $id => $item):
            $subtotal = $item['price'] * $item['quantity'];
        ?>
            <tr>
                <td><?= htmlspecialchars($item['name']); ?></td>
                <td><?= number_format($item['price'], 2); ?> €</td>
                <td>
                    <form action="cart.php" method="post" class="quantity-form">
                        <input type="hidden" name="id" value="<?= $id ?>">
                        <input type="number" name="quantity" value="<?= $item['quantity'] ?>" min="1" class="quantity-input">
                        <button type="submit" class="update-btn">Update</button>
                    </form>
                </td>
                <td><?= number_format($subtotal, 2); ?> €</td>
                <td><a href="cart.php?remove=<?= $id; ?>">Remove</a></td>
            </tr>
        <?php endforeach; ?>
        <tr>
            <td colspan="3"><strong>Total</strong></td>
            <td colspan="2"><strong><?= number_format(getCartTotal(), 2); ?> €</strong></td>
        </tr>
    </table>
    <form action="cart.php" method="get">
        <button type="submit" name="order" class="order-btn">Order now</button>
    </form>
<?php else: ?>
    <p>Your cart is empty.</p>
<?php endif;

if (isset($_GET['order']) && !empty($_SESSION['cart'])): ?>
    <h2>Shipping Information</h2>
    <form action="process_order.php" method="post">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br>

        <label for="fname">First Name:</label>
        <input type="text" id="fname" name="fname" required><br>

        <label for="lname">Last Name:</label>
        <input type="text" id="lname" name="lname" required><br>

        <label for="address">Address:</label>
        <input type="text" id="address" name="address" required><br>

        <label for="housenumber">House Number:</label>
        <input type="text" id="housenumber" name="housenumber" required><br>

        <label for="city">City:</label>
        <input type="text" id="city" name="city" required><br>

        <label for="postal_code">Postal Code:</label>
        <input type="text" id="postal_code" name="postal_code" required><br>

        <label for="country">Country:</label>
        <input type="text" id="country" name="country" required><br>

        <label for="phone">Phone Number:</label>
        <input type="tel" id="phone" name="phone"><br>

        <input type="submit" value="Place Order">
    </form>
<?php endif; ?>
Enter fullscreen mode Exit fullscreen mode
  1. Including Dependencies
    The first line require_once 'incall.php'; ensures that the script includes the necessary external PHP file (incall.php), which might contain functions or database connections needed for the cart operations.

  2. Cart Operations
    Removing Items: If the URL contains a remove parameter (i.e., ?remove=someID), the script calls the removeFromCart() function to delete the item with the corresponding ID from the cart. If the operation is successful, a success message is stored in the session and the user is redirected to cart.php to refresh the page.

Updating Cart Quantity: When the user submits a form to change the quantity of a product, the script checks if the request method is POST and validates if both the product ID and the quantity are provided. It then calls updateCartQuantity() to update the cart and stores a success message in the session. The page is refreshed after the operation.

  1. Displaying Success/Error Messages
    A loop checks for any success_message or error_message stored in the session. If found, the messages are displayed in green (success) or red (error) and then cleared from the session.

  2. Displaying Cart Items
    If the session contains any cart data, the script generates an HTML table displaying:

Product name.
Price per unit, formatted to 2 decimal places.
Quantity with a form that allows users to update the quantity.
Subtotal for each product (price multiplied by quantity).
Remove link that allows users to delete the item from the cart by passing the product ID via the URL.
The total price of all items in the cart is calculated by calling the getCartTotal() function.

  1. Placing an Order If the cart contains items, the user is presented with an “Order now” button, which triggers the order process. When clicked, the page shows a form where the user must enter shipping information, including:

Email address
First and last name
Address details (address, house number, city, postal code, country)
Phone number (optional)
After submitting the form, the data is sent to process_order.php, where the order will be handled.

  1. Empty Cart Case If there are no items in the cart (i.e., the cart is empty), the script displays a message: “Your cart is empty.”

Summary of Key Functions:
removeFromCart($id): Removes an item from the cart based on the product ID.
updateCartQuantity($id, $quantity): Updates the quantity of a specific product in the cart.
getCartTotal(): Calculates and returns the total price of all items in the cart.
This code offers basic cart management, including adding, removing, and updating items, as well as proceeding to checkout with user-inputted shipping details.

Top comments (0)