This class was designed to create a shopping cart using PHP and PDO. The class can store the cart data using session or cookies. It can also include product details by pulling product information from the database.
First, include the Cart class in your PHP file:
- Clone the repository or download the zip file.
- Create a new database and import the
database.sql
file located in thedb
folder. - Configure your database credentials in
config/db.php
. - Run the project in your local server.
include_once 'Cart.php';
Next, create a new instance of the Cart class, passing the desired parameters:
/*
new Cart(useSession, useCookie, taxPercent, dbconnection)
*/
$cart = new Cart(true, false, 18);
$database = new Database();
$conn = $database->getConnection();
$cart = new Cart(true, false, 18, $conn);
You can add an item to the cart using the addItem method:
$cart->addItem($productId, $quantity, $price);
$cart->addItem($productId, $quantity, $price, 'Product');
You can update the quantity of an item in the cart using the updateItemQuantity method:
$cart->updateItemQuantity($productId, $quantity);
You can remove an item from the cart using the removeItem method:
$cart->removeItem($productId);
You can clear the entire cart using the clearCart method:
$cart->clearCart();
You can clear the entire cart using the clearCart method:
$cart->clearCart();
You can retrieve the cart data using the following methods:
$cart->getItems();
$cart->getItemCount();
$cart->getTotalQuantity();
$cart->getSubtotal();
$cart->getTaxAmount();
$cart->getTotal();
You can clear the session and cookie data using the following methods:
$cart->clearSession();
$cart->clearCookie();
You can retrieve the product details from the database using the getProductDetails method:
$cart->getProductDetails($productId);
The getCartDetails() function returns cart details. The returned details include:
- subtotal
- tax amount
- item count
- total quantity
- total (including tax)
- item data
$cart->getCartDetails();
In this way, using the cart class, you can add products, update their quantity, remove them, or completely clean the cart. You can store the cart information in the $cart Data array and use it to display it on the display page.