Project Overview
A Shopping Cart is a fundamental feature of any e-commerce website, allowing users to add, view, update, and remove products before proceeding to checkout. This project covers product listing, session-based cart management, and dynamic cart updates using PHP and MySQL.
Prerequisites
Ensure you have the following:
- Web Server: Apache (using XAMPP, WAMP, or MAMP)
- PHP: Version 7.4 or higher
- MySQL: For database management
- Code Editor: VS Code, Sublime Text, PHPStorm, etc.
- Composer: For dependency management (optional)
- Basic Understanding of Sessions, Forms, and CRUD Operations in PHP
Step-by-Step Procedure
1. Setting Up the Development Environment
- Install XAMPP:
- Download from XAMPP Official Website.
- Follow the installation wizard and install it in the default directory.
- Start Apache and MySQL:
- Open the XAMPP Control Panel.
- Start the Apache and MySQL modules.
- Install Composer (Optional):
- If you plan to use any PHP packages or libraries, install Composer from Composer Official Website.
2. Creating the Database
- Access phpMyAdmin:
- Navigate to
http://localhost/phpmyadmin/
in your browser.
- Navigate to
- Create a New Database:
- Click on “New” in the left sidebar.
- Name the database
shopping_cart
. - Choose “utf8mb4_unicode_ci” as the collation.
- Click “Create”.
- Create a
products
Table:- Select the
shopping_cart
database. - Click on “New” to create a table.
- Define the table with the following fields:
- Click “Save”.
- Select the
- Populate the
products
Table:- Insert sample products manually via phpMyAdmin or create an admin interface to add products later.
3. Project Structure
Organize your project files as follows:
shopping-cart/
├── vendor/ # Composer dependencies (if any)
├── assets/
│ ├── css/
│ │ └── styles.css
│ ├── images/
│ │ └── (product images)
│ └── js/
│ └── scripts.js
├── config/
│ └── db.php
├── templates/
│ ├── header.php
│ └── footer.php
├── index.php
├── product.php
├── cart.php
├── add_to_cart.php
├── update_cart.php
├── remove_from_cart.php
├── checkout.php
├── order_success.php
├── README.md
└── composer.json
4. Configuration
a. Database Connection (config/db.php
)
Create a file named db.php
inside the config
directory to handle database connections.
<?php
// config/db.php
$host = 'localhost';
$db = 'shopping_cart';
$user = 'root'; // Default XAMPP MySQL user
$pass = ''; // Default XAMPP MySQL password is empty
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Enable exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Fetch associative arrays
PDO::ATTR_EMULATE_PREPARES => false, // Disable emulation
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
// Handle connection errors
http_response_code(500);
echo "Database connection failed.";
exit;
}
?>
5. Creating Reusable Templates
a. Header (templates/header.php
)
<?php
// templates/header.php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Shopping Cart</title>
<link rel="stylesheet" href="/shopping-cart/assets/css/styles.css">
</head>
<body>
<header>
<h1>My E-commerce Store</h1>
<nav>
<a href="/shopping-cart/index.php">Home</a>
<a href="/shopping-cart/cart.php">Cart (<?php echo isset($_SESSION['cart']) ? count($_SESSION['cart']) : 0; ?>)</a>
</nav>
</header>
<main>
b. Footer (templates/footer.php
)
<?php
// templates/footer.php
?>
</main>
<footer>
<p>© <?php echo date("Y"); ?> Your Company Name</p>
</footer>
<script src="/shopping-cart/assets/js/scripts.js"></script>
</body>
</html>
6. Styling the Application (assets/css/styles.css
)
Add basic styles to enhance the appearance.
/* assets/css/styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header, footer {
background-color: #333;
color: #fff;
padding: 10px 20px;
}
header h1, footer p {
margin: 0;
}
nav a {
color: #fff;
margin-right: 15px;
text-decoration: none;
}
main {
padding: 20px;
}
.product {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 20px;
display: flex;
}
.product img {
max-width: 150px;
margin-right: 15px;
}
.product-details {
flex: 1;
}
button {
padding: 8px 12px;
background-color: #28a745;
color: #fff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.cart-table {
width: 100%;
border-collapse: collapse;
}
.cart-table th,
.cart-table td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
.cart-table th {
background-color: #f4f4f4;
}
.total {
text-align: right;
margin-top: 20px;
font-size: 1.2em;
}
.error {
background-color: #f8d7da;
color: #842029;
padding: 15px;
margin-bottom: 20px;
border: 1px solid #f5c2c7;
border-radius: 4px;
}
.success {
background-color: #d1e7dd;
color: #0f5132;
padding: 15px;
margin-bottom: 20px;
border: 1px solid #badbcc;
border-radius: 4px;
}
7. Displaying Products (index.php
)
This page lists all available products.
<?php
// index.php
require 'config/db.php';
require 'templates/header.php';
// Fetch all products
$stmt = $pdo->query('SELECT * FROM products');
$products = $stmt->fetchAll();
?>
<h2>Available Products</h2>
<?php if ($products): ?>
<?php foreach ($products as $product): ?>
<div class="product">
<?php if ($product['image']): ?>
<img src="/shopping-cart/assets/images/<?php echo htmlspecialchars($product['image']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
<?php else: ?>
<img src="/shopping-cart/assets/images/default.png" alt="No Image">
<?php endif; ?>
<div class="product-details">
<h3><?php echo htmlspecialchars($product['name']); ?></h3>
<p><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>
<p><strong>Price:</strong> $<?php echo number_format($product['price'], 2); ?></p>
<form action="add_to_cart.php" method="POST">
<input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
<button type="submit">Add to Cart</button>
</form>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<p>No products available.</p>
<?php endif; ?>
<?php
require 'templates/footer.php';
?>
8. Adding Products to Cart (add_to_cart.php
)
This script handles adding products to the shopping cart stored in the session.
<?php
// add_to_cart.php
session_start();
require 'config/db.php';
// Check if product_id is set
if (isset($_POST['product_id'])) {
$product_id = (int)$_POST['product_id'];
// Fetch product details
$stmt = $pdo->prepare('SELECT * FROM products WHERE id = ?');
$stmt->execute([$product_id]);
$product = $stmt->fetch();
if ($product) {
// Initialize cart if not set
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Check if product is already in cart
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] += 1;
} else {
// Add new product to cart
$_SESSION['cart'][$product_id] = [
'id' => $product['id'],
'name' => $product['name'],
'price' => $product['price'],
'quantity' => 1
];
}
// Redirect back to products page
header('Location: index.php');
exit;
} else {
// Invalid product ID
echo "Invalid product.";
}
} else {
// No product ID provided
echo "No product selected.";
}
?>
9. Viewing the Cart (cart.php
)
This page displays all products added to the cart, allows quantity updates, and removal of items.
<?php
// cart.php
require 'config/db.php';
require 'templates/header.php';
// Handle form submissions for updating quantities or removing items
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['update_cart'])) {
foreach ($_POST['quantities'] as $product_id => $quantity) {
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] = max(1, (int)$quantity);
}
}
}
if (isset($_POST['remove_item'])) {
$remove_id = (int)$_POST['remove_item'];
if (isset($_SESSION['cart'][$remove_id])) {
unset($_SESSION['cart'][$remove_id]);
}
}
// Redirect to avoid form resubmission
header('Location: cart.php');
exit;
}
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$total = 0;
?>
<h2>Your Shopping Cart</h2>
<?php if ($cart): ?>
<form action="cart.php" method="POST">
<table class="cart-table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($cart as $item):
$subtotal = $item['price'] * $item['quantity'];
$total += $subtotal;
?>
<tr>
<td><?php echo htmlspecialchars($item['name']); ?></td>
<td>$<?php echo number_format($item['price'], 2); ?></td>
<td>
<input type="number" name="quantities[<?php echo $item['id']; ?>]" value="<?php echo $item['quantity']; ?>" min="1">
</td>
<td>$<?php echo number_format($subtotal, 2); ?></td>
<td>
<button type="submit" name="remove_item" value="<?php echo $item['id']; ?>">Remove</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="total">
<strong>Total: $<?php echo number_format($total, 2); ?></strong>
</div>
<button type="submit" name="update_cart">Update Cart</button>
</form>
<a href="checkout.php">Proceed to Checkout</a>
<?php else: ?>
<p>Your cart is empty. <a href="index.php">Shop now</a>.</p>
<?php endif; ?>
<?php
require 'templates/footer.php';
?>
10. Checking Out (checkout.php
)
This page simulates the checkout process. In a real-world scenario, you would integrate a payment gateway here.
<?php
// checkout.php
require 'config/db.php';
require 'templates/header.php';
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$total = 0;
foreach ($cart as $item) {
$total += $item['price'] * $item['quantity'];
}
// Simulate order processing
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// In a real application, process payment here
// Clear the cart
unset($_SESSION['cart']);
// Redirect to order success page
header('Location: order_success.php');
exit;
}
?>
<h2>Checkout</h2>
<?php if ($cart): ?>
<table class="cart-table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody>
<?php foreach ($cart as $item):
$subtotal = $item['price'] * $item['quantity'];
?>
<tr>
<td><?php echo htmlspecialchars($item['name']); ?></td>
<td>$<?php echo number_format($item['price'], 2); ?></td>
<td><?php echo $item['quantity']; ?></td>
<td>$<?php echo number_format($subtotal, 2); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="total">
<strong>Total: $<?php echo number_format($total, 2); ?></strong>
</div>
<form action="checkout.php" method="POST">
<button type="submit">Confirm Order</button>
</form>
<?php else: ?>
<p>Your cart is empty. <a href="index.php">Shop now</a>.</p>
<?php endif; ?>
<?php
require 'templates/footer.php';
?>
11. Order Success Page (order_success.php
)
This page confirms that the order has been placed successfully.
<?php
// order_success.php
require 'templates/header.php';
?>
<h2>Order Successful</h2>
<p>Thank you for your purchase! Your order has been placed successfully.</p>
<a href="index.php">Continue Shopping</a>
<?php
require 'templates/footer.php';
?>
12. Testing the Application
- Add Products to the Cart:
- Navigate to
http://localhost/shopping-cart/index.php
. - Click on “Add to Cart” for one or more products.
- Ensure that the cart count in the navigation updates accordingly.
- Navigate to
- View the Cart:
- Navigate to
http://localhost/shopping-cart/cart.php
. - Verify that the selected products appear with correct quantities and subtotals.
- Navigate to
- Update Quantities:
- Change the quantity of a product and click “Update Cart”.
- Ensure that the subtotal and total update correctly.
- Remove Items:
- Click on “Remove” next to a product.
- Ensure that the product is removed from the cart.
- Proceed to Checkout:
- Navigate to
http://localhost/shopping-cart/checkout.php
. - Review the order summary and click “Confirm Order”.
- Verify that you are redirected to the Order Success page and the cart is cleared.
- Navigate to
- Handle Empty Cart Scenarios:
- Ensure that appropriate messages are displayed when the cart is empty.
13. Deployment Considerations
When deploying your Shopping Cart to a live server, consider the following:
- Secure Sessions:
- Use secure session handling practices to protect user sessions.
- Integrate Payment Gateway:
- Implement a secure payment gateway (e.g., Stripe, PayPal) to handle real transactions.
- Input Validation and Sanitization:
- Thoroughly validate and sanitize all user inputs to prevent SQL injection and XSS attacks.
- Use HTTPS:
- Ensure that your website uses HTTPS to secure data transmission.
- Protect Against CSRF:
- Implement CSRF tokens in forms to protect against Cross-Site Request Forgery attacks.
- Error Handling:
- Provide user-friendly error messages without exposing sensitive information.
- Optimize Performance:
- Implement caching strategies and optimize database queries for better performance.
- Regular Backups:
- Schedule regular backups of your database to prevent data loss.
- Scalability:
- Design your application to handle increased traffic and data volume as your business grows.
14. Enhancements and Best Practices
- User Authentication:
- Implement user accounts with login functionalities to track orders and save carts.
- Order History:
- Allow users to view their past orders and order statuses.
- Product Categories and Filters:
- Organize products into categories and implement filtering options for easier navigation.
- Search Functionality:
- Add a search bar to help users find products quickly.
- Responsive Design:
- Ensure that the shopping cart is mobile-friendly and responsive across devices.
- Inventory Management:
- Implement stock management to track product availability.
- Coupon and Discount Codes:
- Allow users to apply discount codes during checkout.
- Email Notifications:
- Send order confirmation emails to users upon successful checkout.
- Security Enhancements:
- Implement measures like CAPTCHA in forms to prevent automated abuse.
- Analytics Integration:
- Integrate analytics tools to monitor user behavior and sales performance.