
in this part we're gonna :
-configure our database with php
-define a header page containing our bootstrap components
keymarks:
Try-Catch Block for Connection
Creates a PDO object - PHP's interface for database interaction
The DSN (Data Source Name) specifies:
Database type: mysql
Host: localhost
Database name: restaurant_db
Character set: utf8 (handles special characters and accents)
Configures PDO to throw exceptions when SQL errors occur
Makes debugging easier by providing detailed error information
If connection fails (wrong credentials, MySQL server stopped, etc.)
Displays the error and stops script execution with die()
index .php:
session_start() - Begins or resumes a session (to track logged-in users)
include 'header.php' - Includes the navigation bar and HTML head section
include 'config/database.php' - Includes the database connection code
The HTML section:
Creates a centered welcome message with a restaurant emoji ?️
Displays "Discover our best dishes"
Provides a button linking to menu.php (the menu page)
register.php:
Registration logic:
Checks if the form was submitted (if ($_POST))
Retrieves name, email, and password from the form
Hashes the password using password_hash() - NEVER store plain passwords!
Uses a prepared statement (prevents SQL injection)
Inserts the new user into the database
Security Note: After registration, it just echoes "User created" - a real app would redirect to login page.
login.php:
Notice the paths: Uses ../ (go up one directory) because this file appears to be in a subfolder.
Looks up the user by their email address
Fetches the user record as an associative array(fetch_assoc)
password_verify() checks if the submitted password matches the stored hash
If successful, stores the entire user object in the session
Admin users → sent to admin/dashboard.php
Regular users → sent to index.php (homepage)
I'll explain these PHP files that implement a complete shopping cart and checkout system for the restaurant.
## **1. menu.php** (Product Catalog Page)
### Database Query
```php
$stmt = $pdo->query("SELECT * FROM menu_items");
$menus = $stmt->fetchAll(PDO::FETCH_ASSOC);
```
- Fetches all menu items (dishes) from the database
### Cart Counter
```php
$count = isset($_SESSION['cart']) ? array_sum($_SESSION['cart']) : 0;
```
- Calculates total number of items in cart
- `array_sum($_SESSION['cart'])` adds up all quantities (e.g., `['1' => 2, '3' => 1]` = 3 items)
### Cart Button with Badge
```php
<a href="cart.php" class="btn btn-out-dark position-relative">
? Panier
<?php if ($count > 0): ?>
<span class="badge bg-danger"><?= $count ?></span>
<?php endif; ?>
</a>
```
- Shows cart with item count badge
- Bootstrap's `position-relative` + `translate-middle` positions the badge on the corner
### Logout Button
```php
<?php if(isset($_SESSION['user'])): ?>
<a href="auth/logout.php" class="btn btn-danger">? Logout</a>
<?php endif; ?>
```
- Only shows logout button when user is logged in
### Success Message Display
```php
<?php if(isset($_SESSION['success'])): ?>
<div class="alert alert-success"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
<?php endif; ?>
```
- Displays one-time success message (e.g., "Item added to cart")
- Message is deleted after displaying (`unset()`)
### Menu Display Loop
```php
<?php foreach ($menus as $menu): ?>
<div class="col-md-4 mb-4">
<div class="card shadow-sm h-100">
<h5><?= $menu['name'] ?></h5>
<p><?= $menu['description'] ?></p>
<span><?= $menu['price'] ?> €</span>
<a href="add_to_cart.php?id=<?= $menu['id'] ?>">? Ajouter</a>
</div>
</div>
<?php endforeach; ?>
```
- Displays each menu item in a Bootstrap card
- 3 cards per row (`col-md-4` = 4 columns out of 12)
- Each item has an "Add to Cart" button with its ID
---
## **2. add_to_cart.php** (Add to Cart Logic)
```php
session_start();
$id = $_GET['id']; // Get product ID from URL
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = []; // Initialize cart if it doesn't exist
}
// Increment quantity or set to 1
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id]++; // Add one more
} else {
$_SESSION['cart'][$id] = 1; // First one
}
header("Location: menu.php"); // Redirect back to menu
```
**Cart Structure:**
```php
$_SESSION['cart'] = [
1 => 3, // Menu item ID 1, quantity 3
4 => 1, // Menu item ID 4, quantity 1
7 => 2 // Menu item ID 7, quantity 2
];
```
---
## **3. cart.php** (View Cart Page)
### Get Cart Items
```php
$cart = $_SESSION['cart'] ?? []; // Use empty array if cart doesn't exist
if (empty($cart)) {
echo "Panier vide";
exit;
}
$ids = implode(',', array_keys($cart)); // Convert [1,4,7] to "1,4,7"
$stmt = $pdo->query("SELECT * FROM menu_items WHERE id IN ($ids)");
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
```
### Calculate and Display
```php
foreach ($items as $item):
$qty = $cart[$item['id']];
$subtotal = $qty * $item['price'];
$total += $subtotal;
?>
<tr>
<td><?= $item['name'] ?></td>
<td><?= $qty ?></td>
<td><?= $item['price'] ?> €</td>
<td><?= $subtotal ?> €</td>
</tr>
```
### Checkout Button
```php
<a href="checkout.php" class="btn btn-success">Commander</a>
```
---
## **4. checkout.php** (Order Processing)
### Authentication Check
```php
if (!isset($_SESSION['user'])) {
header("Location: auth/login.php"); // Must be logged in
exit;
}
```
### Database Transaction (CRITICAL!)
```php
$pdo->beginTransaction(); // Start transaction
try {
// 1. Create order
$stmt = $pdo->prepare("INSERT INTO orders (user_id, total) VALUES (?, ?)");
$stmt->execute([$_SESSION['user']['id'], $total]);
$order_id = $pdo->lastInsertId();
// 2. Add order items
$stmt = $pdo->prepare("INSERT INTO order_items (order_id, menu_item_id, quantity, price) VALUES (?, ?, ?, ?)");
foreach ($items as $item) {
$qty = $cart[$item['id']];
$stmt->execute([$order_id, $item['id'], $qty, $item['price']]);
}
$pdo->commit(); // Save everything
unset($_SESSION['cart']); // Clear cart
echo "Commande passée avec succès !";
} catch (Exception $e) {
$pdo->rollBack(); // Undo everything on error
echo "Erreur: " . $e->getMessage();
}
```
**Why use a transaction?**
- Ensures both the order AND order items are saved together
- If either fails, everything is rolled back (no partial orders)
---
## Database Schema (Inferred)
```sql
-- Users table
users (id, name, email, password, role)
-- Menu items
menu_items (id, name, description, price)
-- Orders
orders (id, user_id, total, created_at)
-- Order items (many-to-many relation)
order_items (id, order_id, menu_item_id, quantity, price)
```
---
## Complete User Flow
```
1. User visits menu.php
↓
2. Clicks "Ajouter" on a dish
↓
3. add_to_cart.php adds item to session
↓
4. Redirects back to menu.php (shows cart badge with count)
↓
5. User clicks ? Panier button
↓
6. cart.php shows all items with total
↓
7. User clicks "Commander"
↓
8. checkout.php checks if logged in
↓
9. Creates order in database using transaction
↓
10. Clears cart, shows success message
```
---
I'll explain these PHP files that implement the **Admin Panel** for managing menu items and viewing orders.
---
## **Overall Structure**
This is an admin backend system with:
- **Authentication check** for admin-only access
- **CRUD operations** (Create, Read, Update, Delete) for menu items
- **Order management** (view orders and update status)
---
## **1. auth_check.php** (Admin Authentication)
```php
session_start();
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
header("Location: ../auth/login.php");
exit;
}
```
**What it does:**
- Checks if user is logged in AND has role = 'admin'
- If not, redirects to login page
- **This file is included at the top of ALL admin pages** to protect them
**File location:** Appears to be in an `admin/` folder (uses `../auth/login.php` to go up one level)
---
## **2. dashboard.php** (Admin Homepage)
```php
<?php include 'auth_check.php'; ?>
<?php include '../header.php'; ?>
```
**Simple dashboard** with two management cards:
- **Menus** → links to `menu_manage.php`
- **Commandes (Orders)** → links to `orders.php`
---
## **3. menu_manage.php** (List & Delete Menu Items)
### Delete Functionality
```php
if (isset($_GET['delete'])) {
$stmt = $pdo->prepare("DELETE FROM menu_items WHERE id = ?");
$stmt->execute([$_GET['delete']]);
header("Location: menu_manage.php"); // Refresh page after deletion
}
```
- If URL contains `?delete=123`, deletes that menu item
- Uses prepared statement (secure)
### Display Menu Items
```php
$stmt = $pdo->query("SELECT * FROM menu_items");
$menus = $stmt->fetchAll();
foreach ($menus as $menu): ?>
<div>
<?= $menu['name'] ?> - <?= $menu['price'] ?> €
<a href="edit_menu.php?id=<?= $menu['id'] ?>">Modifier</a>
<a href="?delete=<?= $menu['id'] ?>">Supprimer</a>
</div>
<?php endforeach; ?>
```
- Lists all menu items with Edit and Delete links
- Delete link sends to current page with `?delete=` parameter
---
## **4. add_menu.php** (Create New Menu Item)
```php
include 'auth_check.php';
include '../config/database.php';
if ($_POST) {
$name = $_POST['name'];
$desc = $_POST['description'];
$price = $_POST['price'];
$stmt = $pdo->prepare("INSERT INTO menu_items (name, description, price) VALUES (?,?,?)");
$stmt->execute([$name, $desc, $price]);
header("Location: menu_manage.php"); // Redirect back to management page
}
```
**HTML Form:**
```html
<form method="POST">
<input type="text" name="name" placeholder="Nom" required>
<textarea name="description"></textarea>
<input type="number" step="0.01" name="price" placeholder="Prix" required>
<button>Ajouter</button>
</form>
```
**Note:** No styling (missing Bootstrap classes compared to other files)
---
## **5. edit_menu.php** (Update Existing Menu Item)
### Load Existing Data
```php
$id = $_GET['id'];
$stmt = $pdo->prepare("SELECT * FROM menu_items WHERE id = ?");
$stmt->execute([$id]);
$menu = $stmt->fetch(PDO::FETCH_ASSOC);
```
### Update on Form Submission
```php
if ($_POST) {
$stmt = $pdo->prepare("UPDATE menu_items SET name=?, description=?, price=? WHERE id=?");
$stmt->execute([
$_POST['name'],
$_POST['description'],
$_POST['price'],
$id
]);
header("Location: menu_manage.php");
}
```
### Form with Pre-filled Values
```html
<form method="POST">
<input type="text" name="name" value="<?= $menu['name'] ?>">
<textarea name="description"><?= $menu['description'] ?></textarea>
<input type="number" step="0.01" name="price" value="<?= $menu['price'] ?>">
<button>Modifier</button>
</form>
```
---
## **6. orders.php** (List All Orders)
### SQL Query with JOIN
```php
$stmt = $pdo->query("
SELECT orders.*, users.name
FROM orders
JOIN users ON orders.user_id = users.id
ORDER BY orders.created_at DESC
");
```
- Joins `orders` table with `users` to get customer name
- Orders sorted newest first (DESC)
### Display Orders
```php
foreach ($orders as $order): ?>
<div style="border:1px solid #000; margin:10px; padding:10px;">
<h3>Commande #<?= $order['id'] ?></h3>
<p>Client: <?= $order['name'] ?></p>
<p>Total: <?= $order['total'] ?> €</p>
<p>Status: <?= $order['status'] ?></p>
<a href="order_details.php?id=<?= $order['id'] ?>">Voir détails</a>
<a href="update_status.php?id=<?= $order['id'] ?>&status=completed">Valider</a>
</div>
<?php endforeach; ?>
```
---
## **7. order_details.php** (View Single Order Items)
### SQL Query
```php
$stmt = $pdo->prepare("
SELECT oi.*, m.name
FROM order_items oi
JOIN menu_items m ON oi.menu_item_id = m.id
WHERE oi.order_id = ?
");
```
- Gets all items in a specific order
- Joins with `menu_items` to get the dish name
### Display Items
```php
foreach ($items as $item): ?>
<p>
<?= $item['name'] ?>
x <?= $item['quantity'] ?>
= <?= $item['price'] * $item['quantity'] ?> €
</p>
<?php endforeach; ?>
```
---
## **8. update_status.php** (Update Order Status)
```php
$id = $_GET['id'];
$status = $_GET['status'];
$stmt = $pdo->prepare("UPDATE orders SET status=? WHERE id=?");
$stmt->execute([$status, $id]);
header("Location: orders.php");
## File Structure
```
project/
├── admin/
│ ├── auth_check.php
│ ├── dashboard.php
│ ├── menu_manage.php
│ ├── add_menu.php
│ ├── edit_menu.php
│ ├── orders.php
│ ├── order_details.php
│ └── update_status.php
├── auth/
│ └── login.php
├── config/
│ └── database.php
├── header.php
├── index.php
├── menu.php
├── cart.php
├── checkout.php
└── add_to_cart.php
```
---
## Admin Flow Summary
```
1. Admin logs in (role = 'admin')
↓
2. Redirected to dashboard.php
↓
3. Two options:
A. MANAGE MENU:
menu_manage.php (list items)
├── Add → add_menu.php
├── Edit → edit_menu.php
└── Delete → (same page with ?delete=)
B. MANAGE ORDERS:
orders.php (list orders)
├── View details → order_details.php
└── Update status → update_status.php?status=completed
# Course Description: Building a Restaurant Management System with PHP & MySQL
**Duration:** 20-25 hours | Level: beginner to Intermediate
---
## What You'll Build
A complete, professional restaurant management system featuring customer ordering and an admin dashboard. You'll create user authentication, a shopping cart, secure checkout, and full menu management.
## What You'll Learn
- **PHP & PDO** – Secure database connections and prepared statements
- **User Authentication** – Registration, login, password hashing, and role-based access (user vs. admin)
- **Shopping Cart** – Session-based cart with add/remove functionality and quantity management
- **Database Transactions** – Atomic order processing with COMMIT and ROLLBACK
- **Admin Panel** – Complete CRUD operations for menu items and order management
- **Security** – SQL injection prevention, XSS protection, and secure password storage
## Course Features
- 15+ PHP files with complete source code
- MySQL database schema included
- Bootstrap 5 responsive design
- Real-world project for your portfolio
## Who This Is For
Perfect for beginners who know basic PHP and want to build their first complete web application. No MySQL experience required.
## By the End
You'll have a fully functional restaurant system to showcase employers or clients, plus the confidence to build similar applications like e-commerce stores, booking systems, or inventory management tools.
Watch the Content carefully and follow the instructions
Enroll today and build your first professional PHP application!