E-commerce Core Features
                CMU529: Advanced Web Development - Session 9
                Birmingham Newman University
                Lecturer: James Williams
                Product catalogues, shopping cart implementation, and order management systems
                3-hour session • 22 slides • 2 interactive tasks
                
                    Session Timeline:
                    
                        - 10 min: Registration & waiting
 
                        - 20 min: Opening slides
 
                        - 45 min: Task 1
 
                        - 15 min: Break/Catch up
 
                        - 20 min: Secondary slides
 
                        - 45 min: Task 2
 
                        - Remaining: Self-study
 
                    
                 
            
            
            
                Learning Objectives
                
                    - Build product catalogue systems
 
                    - Implement shopping cart functionality
 
                    - Create order management systems
 
                    - Handle inventory management
 
                    - Build checkout processes
 
                
            
            
            
                Product Catalogue
                
                    Product Display System:
                    
                    // Get products with pagination
                    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                    $limit = 12;
                    $offset = ($page - 1) * $limit;
                    
                    $stmt = $pdo->prepare("SELECT * FROM products WHERE active = 1 ORDER BY created_at DESC LIMIT ? OFFSET ?");
                    $stmt->execute([$limit, $offset]);
                    $products = $stmt->fetchAll();
                    
                    // Display products
                    foreach ($products as $product) {
                      echo "<div class='product-card'>";
                      echo "<img src='" . $product['image'] . "' alt='" . $product['name'] . "'>";
                      echo "<h3>" . $product['name'] . "</h3>";
                      echo "<p>$" . number_format($product['price'], 2) . "</p>";
                      echo "<button onclick='addToCart(" . $product['id'] . ")>Add to Cart</button>";
                      echo "</div>";
                    }
                
                
                    - Display products with pagination
 
                    - Show product images and details
 
                    - Add to cart functionality
 
                
            
            
            
                Product Categories
                
                    Category System:
                    
                    // Get categories
                    $stmt = $pdo->query("SELECT * FROM categories ORDER BY name");
                    $categories = $stmt->fetchAll();
                    
                    // Display category menu
                    echo "<div class='category-menu'>";
                    foreach ($categories as $category) {
                      echo "<a href='?category=" . $category['id'] . "'>" . $category['name'] . "</a>";
                    }
                    echo "</div>";
                    
                    // Filter by category
                    if (isset($_GET['category'])) {
                      $categoryId = (int)$_GET['category'];
                      $stmt = $pdo->prepare("SELECT * FROM products WHERE category_id = ? AND active = 1");
                      $stmt->execute([$categoryId]);
                      $products = $stmt->fetchAll();
                    }
                
                
                    - Organize products by categories
 
                    - Filter products by category
 
                    - Create category navigation
 
                
            
            
            
                Shopping Cart
                
                    Cart Implementation:
                    
                    // Add to cart
                    function addToCart($productId, $quantity = 1) {
                      if (!isset($_SESSION['cart'])) {
                        $_SESSION['cart'] = [];
                      }
                    
                      if (isset($_SESSION['cart'][$productId])) {
                        $_SESSION['cart'][$productId] += $quantity;
                      } else {
                        $_SESSION['cart'][$productId] = $quantity;
                      }
                    }
                    
                    // Get cart items
                    function getCartItems() {
                      global $pdo;
                      $cartItems = [];
                    
                      if (isset($_SESSION['cart'])) {
                        $productIds = array_keys($_SESSION['cart']);
                        $placeholders = str_repeat('?,', count($productIds) - 1) . '?';
                        $stmt = $pdo->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
                        $stmt->execute($productIds);
                        $products = $stmt->fetchAll();
                    
                        foreach ($products as $product) {
                          $cartItems[] = [
                            'product' => $product,
                            'quantity' => $_SESSION['cart'][$product['id']]
                          ];
                        }
                      }
                    
                      return $cartItems;
                    }
                
                
                    - Store cart in session
 
                    - Add/remove items
 
                    - Calculate totals
 
                
            
            
            
                Cart Management
                
                    Cart Operations:
                    
                    // Update cart quantity
                    function updateCartQuantity($productId, $quantity) {
                      if ($quantity <= 0) {
                        unset($_SESSION['cart'][$productId]);
                      } else {
                        $_SESSION['cart'][$productId] = $quantity;
                      }
                    }
                    
                    // Remove from cart
                    function removeFromCart($productId) {
                      unset($_SESSION['cart'][$productId]);
                    }
                    
                    // Clear cart
                    function clearCart() {
                      $_SESSION['cart'] = [];
                    }
                    
                    // Get cart total
                    function getCartTotal() {
                      $cartItems = getCartItems();
                      $total = 0;
                    
                      foreach ($cartItems as $item) {
                        $total += $item['product']['price'] * $item['quantity'];
                      }
                    
                      return $total;
                    }
                
                
                    - Update item quantities
 
                    - Remove items from cart
 
                    - Calculate cart totals
 
                
            
            
            
                Checkout Process
                
                    Checkout System:
                    
                    // Process checkout
                    if ($_SERVER["REQUEST_METHOD"] == "POST") {
                      $userId = $_SESSION['user_id'];
                      $cartItems = getCartItems();
                      $total = getCartTotal();
                    
                      try {
                        $pdo->beginTransaction();
                    
                        // Create order
                        $stmt = $pdo->prepare("INSERT INTO orders (user_id, total, status) VALUES (?, ?, 'pending')");
                        $stmt->execute([$userId, $total]);
                        $orderId = $pdo->lastInsertId();
                    
                        // Add order items
                        foreach ($cartItems as $item) {
                          $stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
                          $stmt->execute([$orderId, $item['product']['id'], $item['quantity'], $item['product']['price']]);
                        }
                    
                        $pdo->commit();
                        clearCart();
                        echo "Order placed successfully!";
                    } catch(PDOException $e) {
                        $pdo->rollback();
                        echo "Order failed: " . $e->getMessage();
                      }
                    }
                
                
                    - Create orders in database
 
                    - Use transactions for data integrity
 
                    - Clear cart after successful order
 
                
            
            
            
                Order Management
                
                    Order System:
                    
                    // Get user orders
                    function getUserOrders($userId) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC");
                      $stmt->execute([$userId]);
                      return $stmt->fetchAll();
                    }
                    
                    // Get order details
                    function getOrderDetails($orderId) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT oi.*, p.name, p.image FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
                      $stmt->execute([$orderId]);
                      return $stmt->fetchAll();
                    }
                    
                    // Update order status
                    function updateOrderStatus($orderId, $status) {
                      global $pdo;
                      $stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
                      $stmt->execute([$status, $orderId]);
                    }
                
                
                    - Track order status
 
                    - View order history
 
                    - Manage order details
 
                
            
            
            
                Inventory Management
                
                    Stock Control:
                    
                    // Check stock availability
                    function checkStock($productId, $quantity) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
                      $stmt->execute([$productId]);
                      $product = $stmt->fetch();
                    
                      return $product['stock'] >= $quantity;
                    }
                    
                    // Update stock
                    function updateStock($productId, $quantity) {
                      global $pdo;
                      $stmt = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
                      $stmt->execute([$quantity, $productId]);
                    }
                    
                    // Check stock before checkout
                    $cartItems = getCartItems();
                    foreach ($cartItems as $item) {
                      if (!checkStock($item['product']['id'], $item['quantity'])) {
                        echo "Insufficient stock for " . $item['product']['name'];
                        exit();
                      }
                    }
                
                
                    - Check stock availability
 
                    - Update inventory levels
 
                    - Prevent overselling
 
                
            
            
            
                Product Search
                
                    Search Functionality:
                    
                    // Search products
                    function searchProducts($query, $category = null) {
                      global $pdo;
                      $searchTerm = "%$query%";
                    
                      if ($category) {
                        $stmt = $pdo->prepare("SELECT * FROM products WHERE (name LIKE ? OR description LIKE ?) AND category_id = ? AND active = 1");
                        $stmt->execute([$searchTerm, $searchTerm, $category]);
                      } else {
                        $stmt = $pdo->prepare("SELECT * FROM products WHERE (name LIKE ? OR description LIKE ?) AND active = 1");
                        $stmt->execute([$searchTerm, $searchTerm]);
                      }
                    
                      return $stmt->fetchAll();
                    }
                    
                    // Handle search form
                    if (isset($_GET['search'])) {
                      $searchQuery = trim($_GET['search']);
                      $category = isset($_GET['category']) ? (int)$_GET['category'] : null;
                      $products = searchProducts($searchQuery, $category);
                    }
                
                
                    - Search by product name
 
                    - Search by description
 
                    - Filter by category
 
                
            
            
            
                Task 1: Basic E-commerce System
                
                    Instructions:
                    
                        - Create a basic e-commerce system with:
 
                        
                            - Product catalogue with categories
 
                            - Shopping cart functionality
 
                            - Add/remove items from cart
 
                            - Checkout process
 
                            - Order management system
 
                        
                        - Implement inventory management
 
                        - Add product search functionality
 
                        - Create order history for users
 
                        - Test all e-commerce features
 
                    
                    Time: 45 minutes
                    This task will help you build core e-commerce functionality
                 
            
            
            
                Break Time
                
                    15 Minutes
                    Take a break, ask questions, or catch up on the previous task.
                    Next: Secondary slides and Task 2
                 
            
            
            
                Product Reviews
                
                    Review System:
                    
                    // Add product review
                    function addReview($productId, $userId, $rating, $comment) {
                      global $pdo;
                      $stmt = $pdo->prepare("INSERT INTO reviews (product_id, user_id, rating, comment, created_at) VALUES (?, ?, ?, ?, NOW())");
                      $stmt->execute([$productId, $userId, $rating, $comment]);
                    
                      // Update product average rating
                      updateProductRating($productId);
                    }
                    
                    // Get product reviews
                    function getProductReviews($productId) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT r.*, u.username FROM reviews r JOIN users u ON r.user_id = u.id WHERE r.product_id = ? ORDER BY r.created_at DESC");
                      $stmt->execute([$productId]);
                      return $stmt->fetchAll();
                    }
                    
                    // Update product rating
                    function updateProductRating($productId) {
                      global $pdo;
                      $stmt = $pdo->prepare("UPDATE products SET avg_rating = (SELECT AVG(rating) FROM reviews WHERE product_id = ?) WHERE id = ?");
                      $stmt->execute([$productId, $productId]);
                    }
                
            
            
            
                Wishlist System
                
                    Wishlist Management:
                    
                    // Add to wishlist
                    function addToWishlist($userId, $productId) {
                      global $pdo;
                      $stmt = $pdo->prepare("INSERT IGNORE INTO wishlist (user_id, product_id, created_at) VALUES (?, ?, NOW())");
                      $stmt->execute([$userId, $productId]);
                    }
                    
                    // Get user wishlist
                    function getWishlist($userId) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT p.* FROM wishlist w JOIN products p ON w.product_id = p.id WHERE w.user_id = ? ORDER BY w.created_at DESC");
                      $stmt->execute([$userId]);
                      return $stmt->fetchAll();
                    }
                    
                    // Remove from wishlist
                    function removeFromWishlist($userId, $productId) {
                      global $pdo;
                      $stmt = $pdo->prepare("DELETE FROM wishlist WHERE user_id = ? AND product_id = ?");
                      $stmt->execute([$userId, $productId]);
                    }
                
            
            
            
                Discount System
                
                    Coupon Management:
                    
                    // Apply discount
                    function applyDiscount($code, $total) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT * FROM coupons WHERE code = ? AND active = 1 AND expires_at > NOW()");
                      $stmt->execute([$code]);
                      $coupon = $stmt->fetch();
                    
                      if ($coupon) {
                        if ($coupon['type'] == 'percentage') {
                          $discount = $total * ($coupon['value'] / 100);
                        } else {
                          $discount = $coupon['value'];
                        }
                        return min($discount, $total);
                      }
                    
                      return 0;
                    }
                    
                    // Calculate final total
                    $subtotal = getCartTotal();
                    $discount = applyDiscount($_POST['coupon_code'], $subtotal);
                    $finalTotal = $subtotal - $discount;
                
            
            
            
                Shipping Calculator
                
                    Shipping System:
                    
                    // Calculate shipping cost
                    function calculateShipping($weight, $destination) {
                      $baseCost = 5.00;
                      $perKg = 2.00;
                    
                      $shippingCost = $baseCost + ($weight * $perKg);
                    
                      // Add destination surcharge
                      switch ($destination) {
                        case 'international':
                          $shippingCost += 15.00;
                          break;
                        case 'remote':
                          $shippingCost += 8.00;
                          break;
                      }
                    
                      return $shippingCost;
                    }
                    
                    // Get cart weight
                    function getCartWeight() {
                      $cartItems = getCartItems();
                      $totalWeight = 0;
                    
                      foreach ($cartItems as $item) {
                        $totalWeight += $item['product']['weight'] * $item['quantity'];
                      }
                    
                      return $totalWeight;
                    }
                
            
            
            
                Order Tracking
                
                    Tracking System:
                    
                    // Generate tracking number
                    function generateTrackingNumber() {
                      return 'TRK' . date('Ymd') . strtoupper(substr(md5(uniqid()), 0, 8));
                    }
                    
                    // Update order status
                    function updateOrderStatus($orderId, $status, $trackingNumber = null) {
                      global $pdo;
                      $stmt = $pdo->prepare("UPDATE orders SET status = ?, tracking_number = ?, updated_at = NOW() WHERE id = ?");
                      $stmt->execute([$status, $trackingNumber, $orderId]);
                    
                      // Log status change
                      $stmt = $pdo->prepare("INSERT INTO order_status_log (order_id, status, created_at) VALUES (?, ?, NOW())");
                      $stmt->execute([$orderId, $status]);
                    }
                    
                    // Get order status history
                    function getOrderStatusHistory($orderId) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT * FROM order_status_log WHERE order_id = ? ORDER BY created_at DESC");
                      $stmt->execute([$orderId]);
                      return $stmt->fetchAll();
                    }
                
            
            
            
                Email Notifications
                
                    Email System:
                    
                    // Send order confirmation
                    function sendOrderConfirmation($orderId) {
                      global $pdo;
                      $stmt = $pdo->prepare("SELECT o.*, u.email, u.username FROM orders o JOIN users u ON o.user_id = u.id WHERE o.id = ?");
                      $stmt->execute([$orderId]);
                      $order = $stmt->fetch();
                    
                      $to = $order['email'];
                      $subject = "Order Confirmation #" . $orderId;
                      $message = "Dear " . $order['username'] . ",\n\n";
                      $message .= "Your order has been confirmed.\n";
                      $message .= "Order ID: " . $orderId . "\n";
                      $message .= "Total: $" . number_format($order['total'], 2) . "\n\n";
                      $message .= "Thank you for your purchase!";
                    
                      mail($to, $subject, $message);
                    }
                    
                    // Send shipping notification
                    function sendShippingNotification($orderId, $trackingNumber) {
                      $to = $order['email'];
                      $subject = "Your Order Has Been Shipped";
                      $message = "Your order #$orderId has been shipped.\n";
                      $message .= "Tracking Number: $trackingNumber";
                    
                      mail($to, $subject, $message);
                    }
                
            
            
            
                Admin Panel
                
                    Admin Functions:
                    
                    // Get all orders for admin
                    function getAllOrders() {
                      global $pdo;
                      $stmt = $pdo->query("SELECT o.*, u.username FROM orders o JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC");
                      return $stmt->fetchAll();
                    }
                    
                    // Update product stock
                    function updateProductStock($productId, $newStock) {
                      global $pdo;
                      $stmt = $pdo->prepare("UPDATE products SET stock = ? WHERE id = ?");
                      $stmt->execute([$newStock, $productId]);
                    }
                    
                    // Get sales statistics
                    function getSalesStats() {
                      global $pdo;
                      $stmt = $pdo->query("SELECT COUNT(*) as total_orders, SUM(total) as total_revenue FROM orders WHERE status = 'completed'");
                      return $stmt->fetch();
                    }
                    
                    // Check admin access
                    if (!hasRole('admin')) {
                      header("Location: access-denied.php");
                      exit();
                    }
                
            
            
            
                Payment Integration
                
                    Payment Processing:
                    
                    // Mock payment processing
                    function processPayment($amount, $cardNumber, $expiryDate, $cvv) {
                      // In real implementation, integrate with payment gateway
                      $paymentId = 'PAY' . time() . rand(1000, 9999);
                    
                      // Simulate payment processing
                      if (strlen($cardNumber) == 16 && strlen($cvv) == 3) {
                        return [
                          'success' => true,
                          'payment_id' => $paymentId,
                          'amount' => $amount
                        ];
                      } else {
                        return [
                          'success' => false,
                          'error' => 'Invalid payment details'
                        ];
                      }
                    }
                    
                    // Process payment in checkout
                    $paymentResult = processPayment($finalTotal, $_POST['card_number'], $_POST['expiry'], $_POST['cvv']);
                    if ($paymentResult['success']) {
                      // Continue with order creation
                    } else {
                      echo "Payment failed: " . $paymentResult['error'];
                    }
                
            
            
            
                Task 2: Complete E-commerce Platform
                
                    Instructions:
                    
                        - Build a complete e-commerce platform with:
 
                        
                            - Product reviews and ratings system
 
                            - Wishlist functionality
 
                            - Discount and coupon system
 
                            - Shipping calculator
 
                            - Order tracking system
 
                            - Email notifications
 
                            - Admin panel for management
 
                            - Payment processing integration
 
                        
                        - Implement advanced features
 
                        - Add comprehensive error handling
 
                        - Create responsive design
 
                        - Test all e-commerce functionality
 
                    
                    Time: 45 minutes
                    This task will help you build a professional e-commerce platform
                 
            
            
            
                Session Summary
                
                    - Product catalogues organize and display products effectively
 
                    - Shopping carts manage user selections
 
                    - Checkout processes handle order completion
 
                    - Order management tracks order status
 
                    - Inventory management prevents overselling
 
                    - Search functionality helps users find products
 
                    - Reviews and ratings build trust
 
                    - Admin panels manage e-commerce operations
 
                
                
                    Next Session:
                    Advanced PHP Features & Security - Object-oriented PHP, input validation, and security hardening