Module 12: E-commerce Project
Course: Programming with Free AI Tools — Build Real Websites and Apps
Module: 12 of 17
Audience: Ages 15–25, beginners
Focus: Product catalog, product detail page, and MySQL database schema for an online store using PHP and MySQL.
Core principle: Always verify AI-generated code. Run queries, click through pages, and confirm data is correct before trusting generated output.
Table of Contents
Lesson 12.1: Designing the Store Database Schema
Duration: 60 minutes
Learning objectives
- Design a relational schema for an online store.
- Create
products, categories, and orders tables in MySQL.
- Use primary keys, foreign keys, and appropriate column types.
- Write SQL
CREATE TABLE statements.
- Seed the database with sample products.
Instructor notes
- Use phpMyAdmin (bundled with XAMPP) to create the database
store.
- Explain relationships: a product belongs to a category; an order references a product.
- Show
DECIMAL for prices (never FLOAT for money).
- Emphasize that good schema design prevents messy data later.
- Have students verify tables were created with
DESCRIBE products;.
Presentation outline
- Entities in a store: products, categories, orders (10 min)
- Primary and foreign keys (10 min)
- Column types: INT, VARCHAR, DECIMAL, TEXT, DATETIME (10 min)
- Writing CREATE TABLE SQL (15 min)
- Inserting sample data (15 min)
Demonstration
- Open phpMyAdmin and create database
store.
- Run
CREATE TABLE categories with id and name.
- Run
CREATE TABLE products with category_id foreign key.
- Run
CREATE TABLE orders referencing products.
- Insert 3 sample products and verify with
SELECT FROM products;.
AI prompts
"Design a MySQL schema for a small online store with products, categories, and orders tables. Include primary and foreign keys and the correct column types for prices."
"Write INSERT statements to seed my products table with 5 example electronics items, including name, price, and description."
Starter code
Final code
Exercises
- Add a
stock column (INT) to products and re-run the table creation.
- Create a
customers table with id, name, email and link it to orders.
- Write a
SELECT joining products and categories to show product name + category name.
Homework
- Design and create an
order_items table to support multiple products per order (normalize the schema).
- Insert 5 more products across at least 2 categories and verify with a JOIN query.
Quiz
- Which column type should you use for a price?
a) FLOAT
b) DECIMAL(10,2) ✅
c) VARCHAR
d) TEXT
- What does a primary key do?
a) Styles the table
b) Uniquely identifies each row ✅
c) Stores images
d) Links to CSS
- A foreign key is used to:
a) Speed up the internet
b) Link a column to a primary key in another table ✅
c) Encrypt data
d) Delete the table
- What does
AUTO_INCREMENT do?
a) Deletes old rows
b) Automatically gives each new row a unique id ✅
c) Increments prices
d) Renames the table
- Which SQL statement shows all rows in
products?
a) SHOW products;
b) SELECT FROM products; ✅
c) GET products;
d) LIST products;
Lesson 12.2: Building the Product Catalog
Duration: 60 minutes
Learning objectives
- Connect PHP to MySQL using
mysqli or PDO.
- Query products and display them in a responsive grid.
- Separate database config from page logic.
- Loop through result rows and render cards.
- Guard against SQL errors and empty results.
Instructor notes
- Put DB credentials in a
config.php file (not in every page).
- Prefer PDO for cleaner, safer code; show
prepare for later lessons.
- Use Bootstrap grid (
row/col) for the catalog layout.
- Teach students to check
if ($result->num_rows === 0) and show "No products".
- Verify by loading
catalog.php in the browser.
Presentation outline
- PHP–MySQL connection basics (10 min)
- Writing a SELECT query (10 min)
- Looping results into HTML cards (15 min)
- Bootstrap grid layout (15 min)
- Handling empty/error states (10 min)
Demonstration
- Create
config.php with mysqli_connect(...).
- Create
catalog.php that runs SELECT FROM products.
- Output each product as a Bootstrap card with name, price, image.
- Show the "No products" message when the table is empty.
- Break the query to demonstrate error handling.
AI prompts
"Write PHP code using mysqli that connects to a MySQL database and displays all products from the products table as Bootstrap cards with name, price, and image."
"Show how to keep my database credentials in a separate config.php and include it safely in other pages."
Starter code
Final code
Exercises
- Add the product
description to each card (truncated to 50 characters).
- Filter the catalog by
category_id using a dropdown or query parameter.
- Show the category name by JOINing
categories in the query.
Homework
- Style the catalog with your own CSS and make it fully responsive on mobile.
- Add a search box that filters products by name using a SQL
LIKE query (sanitize the input).
Quiz
- Which function connects PHP to MySQL with mysqli?
a) mysql_open()
b) mysqli_connect() ✅
c) db_connect()
d) pdo()
- How do you include
config.php in another page?
a) import 'config.php';
b) require 'config.php'; ✅
c) link config.php
d) #include
- What does
mysqli_fetch_assoc() return?
a) A numbered array
b) An associative array of the row ✅
c) A JSON string
d) A boolean
- Why use
htmlspecialchars() when echoing data?
a) To bold the text
b) To prevent XSS by escaping HTML ✅
c) To speed up PHP
d) It is required by MySQL
- What should you show if a query returns zero rows?
a) A blank page
b) A friendly "No products found" message ✅
c) A fatal error
d) The SQL query
Lesson 12.3: Building the Product Detail Page
Duration: 45 minutes
Learning objectives
- Read a product id from the URL query string.
- Fetch a single product with a
WHERE id = ? query.
- Display full product details (image, price, description).
- Use prepared statements to avoid SQL injection.
- Handle missing/invalid ids with a 404-style message.
Instructor notes
- Transition from
mysqli to a prepared statement here for security.
- Always cast/validate the
id from $_GET (e.g., (int)).
- Show the difference between safe
? placeholders and unsafe string concatenation.
- Reinforce: never put raw
$_GET values directly into SQL.
Presentation outline
- Reading
$_GET['id'] (5 min)
- Why prepared statements matter (10 min)
SELECT ... WHERE id = ? with bind (15 min)
- Rendering the detail view (10 min)
- Handling not-found (5 min)
Demonstration
- Create
product.php?id=1.
- Cast id:
$id = (int) ($_GET['id'] ?? 0);.
- Prepare
SELECT FROM products WHERE id = ?, bind, execute.
- Display full details; if no row, show "Product not found".
- Demonstrate a malicious
?id=1 OR 1=1 attempt and show the safe behavior.
AI prompts
"Write a PHP product detail page using a mysqli prepared statement that gets a product by id from $_GET and shows 404 if not found."
"Explain SQL injection and show why using prepared statements with ? placeholders is safer than concatenating $_GET into a query."
Starter code
Final code
Exercises
- Add a "Add to cart" button (links to cart logic from Lesson 12.4).
- Show the category name by joining
categories.
- Display a placeholder image when
image is empty.
Homework
- Add a related-products section showing other items in the same category.
- Write a prepared statement that updates a product's
stock when "purchased".
Quiz
- How do you safely read an id from the URL?
a) $_GET['id'] without checks
b) Cast it: (int) ($_GET['id'] ?? 0) ✅
c) $_POST['id']
d) request.id
- What prevents SQL injection in this lesson?
a) Comments
b) Prepared statements with ? placeholders ✅
c) Uppercase SQL
d) Bootstrap
- What does
mysqli_stmt_bind_param($stmt, 'i', $id) do?
a) Deletes the row
b) Binds an integer parameter to the query ✅
c) Connects to the DB
d) Renders HTML
- What should happen if the product id does not exist?
a) Show a blank page
b) Show a "Product not found" message ✅
c) Crash the server
d) Redirect to Google
- Why is concatenating
$_GET into SQL dangerous?
a) It is slower
b) Attackers can inject their own SQL commands ✅
c) MySQL rejects it
d) It breaks Bootstrap
Lesson 12.4: Cart Basics and Connecting Pages
Duration: 45 minutes
Learning objectives
- Store cart items using PHP sessions.
- Add a product to the cart from the detail page.
- Display cart contents with totals.
- Link catalog, detail, and cart pages together.
- Remove items from the cart.
Instructor notes
- Start every cart page with
session_start();.
- Store cart as
$_SESSION['cart'][$id] = quantity.
- Compute totals in PHP, not trusting the client.
- Verify the flow end-to-end in the browser.
- Keep it simple; full checkout comes in the Final Project.
Presentation outline
- PHP sessions intro (10 min)
- Adding to cart with
$_SESSION (10 min)
- Displaying cart + total (15 min)
- Removing items (5 min)
- Wiring pages together (5 min)
Demonstration
- Add
session_start(); and a form on product.php posting to cart.php?action=add&id=1.
- In
cart.php, increment $_SESSION['cart'][$id].
- Render cart table joining product data and sum the total.
- Add a "Remove" link that unsets the item.
- Click through catalog → detail → cart to verify.
AI prompts
"Write PHP code using sessions to add products to a shopping cart, display the cart with a total price, and allow removing items."
"Explain how PHP sessions work and why session_start() must be called before any output."
Starter code
Final code
Exercises
- Add a quantity update control (+ / −) on the cart page.
- Persist the cart to the database
orders table on a "Checkout" button.
- Show the number of cart items in the header of every page.
Homework
- Build a complete mini-store: catalog → detail → cart → simple checkout that inserts into
orders.
- Write a one-page README explaining your database schema and how the pages connect.
Quiz
- What must be called before any output to use PHP sessions?
a) session_open()
b) session_start() ✅
c) start_session()
d) session()
- Where are PHP session values stored between page loads?
a) In the URL
b) On the server, referenced by a session id ✅
c) In the browser cache only
d) In a cookie file the user can edit freely
- How do you add a product to
$_SESSION['cart']?
a) $_SESSION['cart'][$id] = 1;
b) Both increment and set are valid ✅
c) cart.add($id)
d) session.cart.push
- Why compute the total in PHP rather than trusting the browser?
a) PHP is faster
b) Client values can be tampered with ✅
c) JavaScript cannot add
d) It is required by law
- What does
unset($_SESSION['cart'][$id]) do?
a) Empties the whole cart
b) Removes that one item from the cart ✅
c) Logs the user out
d) Deletes the product
End of Module 12. Verify every query and click through each page before submitting your store.
الوحدة 12: مشروع المتجر الإلكتروني
الدورة: البرمجة بأدوات الذكاء الاصطناعي المجانية — بناء مواقع وتطبيقات حقيقية | الجمهور: أعمار 15–25، مبتدئون | هدف الوحدة: بناء كتالوج منتجات وصفحة تفاصيل المنتج ومخطط قاعدة بيانات لمتجر باستخدام PHP و MySQL.
المبدأ الأساسي: تحقق دائماً من الكود المولد. تشغيل الاستعلامات، واختبار كل صفحة، قبل اعتماد النتيجة.
الدرس 12.1: تصميم مخطط قاعدة بيانات المتجر
المدة: 60 دقيقة
ملخّص: تصميم مخطط علائلي للمنتجات والفئات والطلبات. إنشاء جداول MySQL مع foreign keys و DECIMAL للأسعار.
الدرس 12.2: بناء كتالوج المنتجات
المدة: 60 دقيقة
ملخّص: الاتصال بـ MySQL وعرض المنتجات في شبكة متجاوبة (Bootstrap grid). استخدام PDO و prepared statements.
الدرس 12.3: بناء صفحة تفاصيل المنتج
المدة: 45 دقيقة
ملخّص: قراءة id من URL، جلب منتج واحد بـ prepared statement، وعرض التفاصيل الكاملة مع معالجة الحالات غير الموجودة.
الدرس 12.4: أساسيات سلة التسوص وربط الصفحات
المدة: 45 دقيقة
ملخّص: تخزين عناصر السلة في جلسات PHP، إضافة/إزالة منتجات، عرض المجموع، وربط الكتالوج بالتفاصيل بالسلة.