PHP × MySQL
Educational Project Catalogue — Terra Nexus Internship Programme

20 Advanced
PHP & MySQL Projects

A curated collection of full-stack web applications built with pure PHP, MySQLi, HTML, and CSS. Every project uses sessions for state management and relational database tables to reflect real-world data design. No PDO. No frameworks. Raw, honest server-side development.

PHP (MySQLi) MySQL HTML5 & CSS3 Sessions Relational Tables
20Projects
3–7Tables Each
100%No Frameworks
Learning Value
Difficulty Intermediate — Mid-level learners with basic PHP knowledge Advanced — Solid understanding of PHP logic and SQL joins required

Project Cards — click any card to expand details
Library Management System
Books · Members · Borrowing Records
Intermediate

A complete library cataloguing and borrowing platform where librarians manage book inventory, register members, and track the full lifecycle of each borrowing transaction — from checkout through return with fine calculation for overdue items.

Core Concepts Used
JOIN queriesSession rolesDate arithmeticFine calculationSearch & filter
Tables
books, members, borrowings, categories, fines
Sessions Used For
Admin vs. member login, cart-style book reservation flow
How the Application Works

The system has two distinct user roles stored in the session: librarian (admin) and member. When a librarian logs in, the session stores their role, enabling access to administrative panels for adding or editing books and registering members. Members can browse the catalogue, search by author or category, and request borrowing through a session-held reservation queue.

Key Database Relationships
  • The borrowings table has foreign keys linking to both members and books, creating a many-to-many relationship resolved through this junction table.
  • The books table links to categories via a category_id, enabling filtered browsing.
  • The fines table references a borrowing_id and is populated only when a book is returned late, with the fine amount computed using MySQL's DATEDIFF function.
What Students Learn

Multi-role session management, complex JOIN queries across three tables at once, and real-world date/time calculations — skills directly applicable to any transactional web application.

Hospital Patient Management System
Patients · Doctors · Appointments · Records
Advanced

A clinical workflow application where patients book appointments with specific doctors, and doctors access patient histories, log diagnoses, and prescribe medications — all with department-level access control enforced through sessions.

Core Concepts Used
Role-based accessMany-to-manyAppointment slotsMedical recordsStatus workflow
Tables
patients, doctors, departments, appointments, medical_records, prescriptions
Sessions Used For
Patient, doctor, and admin role separation with per-view data filtering
How the Application Works

Upon login, the session stores the user's role (patient, doctor, admin) and their ID. A patient's dashboard shows only their appointments and records, because every SQL query filters by the session's patient_id. A doctor sees only appointments assigned to them. An admin sees the full hospital overview and manages departments and doctor assignments.

Key Database Relationships
  • Doctors belong to a department via a department_id foreign key in the doctors table.
  • Appointments join patients and doctors, carrying a status column (pending, confirmed, completed, cancelled) that drives the workflow state machine.
  • Medical records link to a completed appointment, ensuring a record cannot exist without an associated visit.
  • Prescriptions link to a medical_record_id, creating a chain: patient → appointment → record → prescription.
What Students Learn

Building deeply relational schemas, implementing a status-driven workflow, and writing JOIN queries that traverse four or more tables — a critical skill for enterprise application development.

E-Commerce Store with Cart
Products · Orders · Cart · Reviews
Advanced

A functional online shop where users browse products by category, add items to a session-based shopping cart, place orders with payment status tracking, and leave reviews — while admins manage inventory and order fulfilment.

Core Concepts Used
Session cartOrder lifecycleProduct variantsInventory trackingAggregate queries
Tables
products, categories, orders, order_items, users, reviews
Sessions Used For
Persistent cart across pages, logged-in user identity, flash messages after checkout
How the Application Works

The shopping cart is stored entirely in the PHP session as an associative array of product_id → quantity. This allows guest browsing and carting without a database write. On checkout, the session cart is converted into a permanent order record, order_items rows are inserted for each line item, and the session cart is cleared. Stock levels in the products table are decremented atomically.

Key Database Relationships
  • The order_items table is the junction between orders and products, storing quantity and unit_price at the time of purchase — important because product prices may change later.
  • Products belong to categories via category_id, enabling hierarchical navigation.
  • Reviews link to both users and products, unique-constrained per user per product to prevent duplicates.
What Students Learn

Why temporary data belongs in sessions and permanent data in the database, and how to atomically convert one into the other — a pattern used in virtually every transactional web system.

Student Result & Grade Management
Students · Courses · Grades · Reports
Intermediate

An academic grading platform where teachers enter marks for each subject, the system auto-calculates GPA, generates printable report cards, and students log in to view their academic history across semesters.

Core Concepts Used
GPA calculationGROUP BYAVG / SUMSemester filteringPrint view
Tables
students, teachers, courses, enrollments, grades, semesters
Sessions Used For
Student vs. teacher login, active semester stored in session to reduce repeated filters
How the Application Works

The active semester is saved in the session when a teacher selects it, so all subsequent grade-entry forms are automatically scoped to that semester without requiring an extra dropdown each time. Students log in and see a dashboard that uses GROUP BY on their grades to compute per-subject averages and a cumulative GPA, displayed in a formatted transcript layout.

Key Database Relationships
  • The enrollments table links students to courses for a given semester, forming the bridge that determines which grades are valid.
  • Grades reference an enrollment_id (not directly a student_id), ensuring a student can only be graded for courses they are enrolled in.
  • Courses link to a teacher via teacher_id, restricting which teacher can enter marks for each course.
What Students Learn

Aggregate SQL functions (AVG, COUNT, SUM, GROUP BY) and how using enrollment as an intermediate entity prevents data integrity problems — a fundamental normalisation concept.

Employee Payroll & Leave System
Employees · Payroll · Departments · Leave
Advanced

A human resources platform that manages employee salary records, monthly payroll generation, leave requests with approval workflows, and department-level reporting — covering core HR operations within a single application.

Core Concepts Used
Payroll calculationLeave balancesApproval workflowDeductionsMonthly reports
Tables
employees, departments, salary_grades, payroll_records, leave_requests, deductions
Sessions Used For
HR admin vs. employee role, multi-step leave application wizard stored in session
How the Application Works

Employees submit multi-day leave requests. The session holds the partially-filled leave form across multiple pages, preventing loss if the user navigates away. HR admins see a pending-approvals queue and can approve or reject with a reason. On approval, the employee's leave_balance is decremented via PHP calculation before the database update.

Key Database Relationships
  • Employees belong to departments via a department_id, and departments have a manager_id that references the employees table itself — a self-referencing foreign key.
  • Payroll records link to employees and reference a salary_grade_id to compute base salary, then apply deductions from a separate deductions table.
  • Leave requests reference the approving manager's employee_id when resolved.
What Students Learn

Self-referencing foreign keys, multi-step session-based forms, and approval workflow state machines — including transactional query concepts ensuring payroll records are never partially written.

Online Voting & Poll System
Elections · Candidates · Votes · Results
Intermediate

A secure digital voting platform where administrators create election campaigns with candidates, registered voters cast a single authenticated vote, and results are tallied in real-time with visual percentage breakdowns.

Core Concepts Used
Vote uniquenessCOUNT aggregateSession authUnique constraintLive results
Tables
elections, candidates, voters, votes, positions
Sessions Used For
Voter authentication, tracking which elections the current voter has already participated in
How the Application Works

Before rendering the voting form, PHP checks both the database (has a vote record with this voter_id and election_id already been inserted?) and the session (was this vote recorded during the current session?). This dual-layer check prevents database-level duplicate votes and form resubmission attacks. The results page runs a COUNT grouped by candidate_id and calculates each candidate's vote percentage in PHP before rendering the progress bars.

Key Database Relationships
  • The votes table has a composite UNIQUE KEY on (voter_id, election_id), making duplicate votes structurally impossible at the database level.
  • Candidates belong to both an election and a position (e.g. President, Secretary), allowing multi-position elections in one campaign.
What Students Learn

Defence-in-depth: enforcing business rules at both the application layer (PHP/session) and the database layer (UNIQUE constraints). Students learn that application logic alone is never sufficient for data integrity.

Hotel Room Reservation System
Rooms · Bookings · Guests · Availability
Advanced

A hotel booking platform where guests search for available rooms by date range, make reservations that update availability in real-time, and managers generate occupancy reports and handle check-in/check-out tracking.

Core Concepts Used
Date range queriesAvailability logicNOT EXISTSBooking overlapRoom types
Tables
rooms, room_types, bookings, guests, amenities, room_amenities
Sessions Used For
Search criteria (check-in, check-out, guests) persisted across the browsing and booking flow
How the Application Works

When a guest enters check-in and check-out dates, those dates are saved in the session. Every subsequent page reads them from the session rather than passing them through URLs. The availability query uses a NOT EXISTS subquery to exclude any room with an overlapping booking: any booking where check_in is before the desired check-out AND check_out is after the desired check-in.

Key Database Relationships
  • Rooms belong to room_types (Single, Double, Suite), which carry the base pricing and capacity.
  • The room_amenities table is a junction between rooms and amenities (Wi-Fi, Pool, Parking), enabling flexible amenity assignment.
  • Bookings link guests to rooms and carry check_in, check_out, and a status field for the check-in lifecycle.
What Students Learn

Date-range overlap logic — one of the most commonly misunderstood SQL concepts. This project forces students to think through all four overlap cases and encode them correctly, a skill applicable to any reservation system.

Blog & Content Management System
Posts · Authors · Comments · Categories
Intermediate

A full-featured publishing platform with author accounts, categorised blog posts, a nested comment system, tag management, and an admin panel for post moderation — built without any CMS framework.

Core Concepts Used
Self-join (comments)Slug routingPaginationTag many-to-manyDraft/publish
Tables
posts, authors, categories, tags, post_tags, comments
Sessions Used For
Author login, draft autosave state, comment pre-fill from previously entered guest name
How the Application Works

Authors log in and are taken to their personal dashboard showing only their own posts. The session holds the author_id, automatically attached to new posts on creation. Guest commenters have their name stored in the session so subsequent comments pre-fill the form. Nested comments are achieved with a self-referencing parent_id column, and the PHP rendering logic recursively builds the comment tree.

Key Database Relationships
  • The post_tags table is a classic junction resolving the many-to-many between posts and tags.
  • Comments reference both a post_id and an optional parent_id (another comment's ID), enabling threading.
  • Posts link to both an author and a category, with an additional status column (draft, published, archived).
What Students Learn

Recursive data structures in SQL, many-to-many relationships, and URL slug-based routing. The self-referencing comment table demonstrates how relational data can model tree structures.

Inventory & Stock Management
Products · Stock · Suppliers · Transactions
Advanced

A warehouse inventory system that tracks product stock levels via a transaction ledger, manages supplier relationships, records purchase orders, and triggers low-stock alerts when quantities fall below defined thresholds.

Core Concepts Used
Stock ledgerRunning totalsSupplier relationsAlert logicTransaction log
Tables
products, categories, suppliers, stock_transactions, purchase_orders, warehouses
Sessions Used For
Active warehouse context, stock adjustment form held in session to prevent double-posting
How the Application Works

Rather than storing current stock as a single number that gets updated, this system uses a ledger approach: every stock movement (receiving goods, selling, adjusting) is logged as a transaction with a type (IN or OUT) and quantity. The current stock level is always computed as SUM(quantity WHERE type=IN) - SUM(quantity WHERE type=OUT). This approach preserves a complete audit trail and is the standard pattern in professional inventory systems.

Key Database Relationships
  • Stock transactions reference both a product_id and a warehouse_id, enabling multi-warehouse tracking.
  • Purchase orders link to suppliers and, upon confirmation, automatically generate IN stock_transactions for each line item.
  • Products link to categories and have a reorder_threshold column used by the alert query.
What Students Learn

The ledger pattern versus the mutable-state pattern is a pivotal architectural lesson. Students also learn to use aggregate queries to derive computed state, and to appreciate why an audit trail is often more valuable than a simple counter.

Event Ticketing Platform
Events · Tickets · Attendees · QR Codes
Advanced

An event management system where organisers create events with tiered ticket categories, attendees purchase tickets that generate unique booking codes, and event staff can validate tickets through a check-in interface.

Core Concepts Used
Unique codesTicket tiersCapacity limitsCheck-in statusSeat counting
Tables
events, ticket_categories, tickets, attendees, venues, bookings
Sessions Used For
Multi-ticket purchase cart, organiser vs. attendee vs. staff role separation
How the Application Works

When an attendee selects tickets, the quantity is added to a session-based cart. The session also temporarily holds a ticket reservation (reducing available count) for a configurable timeout (e.g., 10 minutes) to prevent overbooking during checkout. On payment confirmation, permanent ticket records are inserted with PHP-generated unique booking codes, and the temporary reservation is released. Staff can search a booking code to mark it as used during entry.

Key Database Relationships
  • Ticket categories belong to events and define the price, capacity, and name (VIP, General, Student).
  • Each ticket record represents one seat and links to a booking (purchase transaction) and a category.
  • The available count is derived by querying COUNT of tickets sold per category versus the category's capacity.
What Students Learn

Temporary reservation patterns, concurrency-safe capacity checking using SELECT ... FOR UPDATE concepts, and how to generate and validate unique codes in PHP. The tiered pricing model also teaches polymorphic pricing within a single event.

Online Quiz & Examination System
Quizzes · Questions · Attempts · Results
Intermediate

A timed examination platform where teachers create multi-type quizzes (MCQ, true/false, short answer), students take exams with a countdown timer enforced server-side, and results are auto-scored and stored for review.

Core Concepts Used
Timer sessionsAuto-scoringAnswer storageQuestion typesAttempt history
Tables
quizzes, questions, options, attempts, attempt_answers, users
Sessions Used For
Exam start timestamp (server-side timer), current question position, in-progress answers
How the Application Works

When a student starts an exam, the current Unix timestamp is stored in the session (not just displayed in the browser). Every time a page loads during the exam, PHP compares the current time to the session start time. If the time limit has elapsed, the exam is forcibly submitted regardless of how many questions remain. Answers are temporarily stored in the session as the student progresses, then bulk-inserted on submission, preventing incomplete records in the database.

Key Database Relationships
  • Questions belong to a quiz and have a type field that determines how they are rendered and scored.
  • Options belong to questions and have an is_correct boolean, used for auto-scoring MCQs.
  • Attempt answers link to both an attempt and a question, storing the student's selected option_id or typed text.
What Students Learn

Server-side time enforcement (why the timer must live in PHP sessions, not just JavaScript), polymorphic data (different question types sharing one table), and the importance of inserting data atomically on submission rather than question-by-question.

Restaurant Order & Menu Management
Menu · Orders · Tables · Kitchen Dashboard
Advanced

A point-of-sale style restaurant system where waitstaff take orders per table through a session-based ordering flow, the kitchen sees a live queue of pending items, and managers access sales analytics and menu control.

Core Concepts Used
Table sessionsKitchen queueItem statusBill splittingDaily revenue
Tables
menu_items, categories, restaurant_tables, orders, order_items, staff
Sessions Used For
Active table context for waiter, in-progress order cart before confirmation
How the Application Works

A waiter selects their assigned table at login; the table_id is stored in the session. As they add items to the order, those items accumulate in a session-based cart scoped to that table. Submitting the order inserts it into the database and marks the table as "occupied." The kitchen dashboard auto-refreshes and displays all pending order items grouped by table. When items are marked ready, their status updates; when the bill is requested, the order total is calculated via SUM(unit_price * quantity).

Key Database Relationships
  • Orders link to both a restaurant_table and a staff member, creating accountability per order.
  • Order items link to orders and menu items, storing the price at the time of order to handle future menu price changes.
  • Menu items belong to categories and carry an availability flag toggled by managers in real time.
What Students Learn

Context-scoped sessions (each session represents a specific table's order), status-driven item queues, and the importance of recording prices at transaction time rather than looking them up later — a critical concept for financial accuracy.

Real Estate Property Listing System
Properties · Agents · Inquiries · Saved Listings
Intermediate

A property listing platform where agents publish properties with images and details, buyers search and filter by type, price, and location, save favourites to a personal list, and submit inquiries that go to the responsible agent.

Core Concepts Used
Advanced filtersSaved favouritesAgent assignmentPrice range queryImage gallery
Tables
properties, agents, property_images, property_types, saved_properties, inquiries
Sessions Used For
Buyer login for favourites, search filter persistence, comparison basket (compare 3 properties)
How the Application Works

Search filters (price range, bedrooms, type, location) are stored in the session so a buyer can browse results and navigate back to the search page without losing their criteria. A "Compare" feature stores up to three property IDs in the session array; the comparison page fetches all three and renders them side-by-side. Saving a favourite requires login and simply inserts a record into the saved_properties table, which is unique-constrained on (user_id, property_id).

Key Database Relationships
  • Properties link to an agent and a property_type, with a status field (available, sold, under offer).
  • Property images have a is_primary flag to determine which image appears on listing cards versus the detail gallery.
  • Inquiries link to both the property and the buyer, with the agent_id denormalised for fast notification queries.
What Students Learn

Dynamic SQL construction (building WHERE clauses based on which filters are active), the session-as-comparison-basket pattern, and how to display multiple images per record using a one-to-many relationship.

Expense Tracker & Budget Planner
Transactions · Categories · Budgets · Reports
Intermediate

A personal finance management tool where users log income and expense transactions, set monthly budget limits per category, and receive visual feedback on spending progress with monthly summaries and exportable reports.

Core Concepts Used
Budget vs actualMonthly groupingSUM by categoryRecurring entriesBalance running total
Tables
users, transactions, categories, budgets, recurring_transactions
Sessions Used For
User login, active month/year filter stored in session for consistent dashboard context
How the Application Works

The active month and year are stored in the session so the entire dashboard is scoped to that period. The main summary query groups transactions by category and type (income/expense), summing amounts with MySQL's SUM and GROUP BY. The budget comparison JOINs the budgets table to compare the budgeted amount against the actual spending per category, displaying a percentage-based progress bar for each.

Key Database Relationships
  • Transactions link to users and categories, carrying a type (income or expense) and a transaction_date.
  • Budgets link to users and categories for a specific month/year, allowing per-month budget resets.
  • Recurring transactions are templates with a frequency field; a cron-style PHP check generates actual transaction records from them.
What Students Learn

Multi-dimensional aggregation (group by category AND month), LEFT JOIN usage to include categories with no transactions (showing zero spending), and the concept of derived data versus stored data in financial contexts.

Task & Project Management Tool
Projects · Tasks · Members · Comments
Advanced

A lightweight Trello-style collaborative project tool where teams manage projects with boards, assign tasks to members, track progress through status columns, set priorities, and communicate through task-level comments.

Core Concepts Used
Team membershipTask assignmentStatus boardPriority sortingActivity log
Tables
projects, tasks, users, project_members, task_comments, activity_log
Sessions Used For
Current user identity, active project context, drag-order state for board columns
How the Application Works

Access to each project is gated by a check against the project_members table — the session user_id must exist as a member of the project before any project data is displayed. When a task is moved between status columns (To Do → In Progress → Done), a PHP endpoint updates the task's status field and simultaneously inserts a record into the activity_log table, creating an immutable history of all actions on each task.

Key Database Relationships
  • Project members link users to projects with a role column (owner, editor, viewer), controlling what actions each member can take.
  • Tasks link to projects and optionally to an assignee (a user_id), with status, priority, and due_date columns.
  • Activity log records reference the user who performed the action, the task affected, and the old and new values for auditing.
What Students Learn

Row-level access control using relational membership tables, immutable audit logging as a first-class concern, and how to structure role-based permissions within a shared resource model.

Bus/Transport Ticket Booking System
Routes · Schedules · Seats · Passengers
Advanced

A public transport booking platform where passengers search routes between cities, select departure times, pick available seats from a visual seat map, and complete bookings that block those seats in the database.

Core Concepts Used
Seat blockingRoute graphSchedule querySeat mapBooking codes
Tables
routes, schedules, buses, seats, bookings, passengers
Sessions Used For
Selected route/schedule/seat held in session during multi-step booking flow
How the Application Works

The booking process spans three pages: route selection, seat selection, and passenger details. The session holds the chosen schedule_id and then the seat_id as the user progresses. The seat availability query checks the bookings table for any confirmed booking matching that seat_id and schedule_id. The seat map renders each seat's status (available, booked, selected) using a CSS class driven by the database query result.

Key Database Relationships
  • Routes link origin and destination cities; schedules link to routes and to a specific bus, carrying the departure datetime.
  • Seats belong to a bus (not a schedule), because the same physical seats exist across all journeys on that bus.
  • Bookings combine a seat, a schedule, and a passenger, with a unique constraint on (seat_id, schedule_id) to prevent double-booking.
What Students Learn

Separating physical assets (seats belonging to buses) from transactional records (bookings belonging to schedules), multi-step session flows, and how composite unique constraints protect inventory resources at the database level.

Social Network (Mini Facebook)
Users · Posts · Friends · Notifications
Advanced

A simplified social platform where users create profiles, post updates, send/accept friend requests, react to posts, comment, and receive a personalised feed showing only content from their network.

Core Concepts Used
Friend graphNews feed queryNotification systemReactionsPrivacy levels
Tables
users, posts, friendships, post_reactions, comments, notifications
Sessions Used For
Logged-in user identity, unread notification count cached in session to reduce repeated queries
How the Application Works

The news feed is generated by querying posts WHERE the author_id is IN a subquery that fetches all accepted friend IDs of the session user, combined with a UNION of the user's own posts. The friendships table uses a canonical pair convention (always storing the lower user_id as user_id_1) to avoid duplicate entries. Friend request status (pending, accepted, blocked) drives the UI shown when viewing another user's profile.

Key Database Relationships
  • Friendships are stored with status and direction, requiring careful query construction to retrieve mutual friends.
  • Post reactions link a user to a post with a reaction_type (like, love, etc.), unique-constrained per user per post.
  • Notifications reference the triggering user, the recipient, the action type, and an optional reference ID pointing to the relevant post or comment.
What Students Learn

Graph-like relationships in relational databases, complex feed queries using IN with subqueries, session-cached counters to reduce database load, and the importance of indexing foreign keys in high-traffic tables.

Online Banking Simulation
Accounts · Transfers · Transactions · Statements
Advanced

A simulated retail banking application where users manage multiple accounts, transfer funds between them or to other users, view detailed transaction histories, and download monthly account statements.

Core Concepts Used
Atomic transfersBalance ledgerTransaction log2FA sessionStatement export
Tables
users, accounts, transactions, beneficiaries, transfer_limits, login_history
Sessions Used For
Two-factor authentication flag in session, transaction PIN verification, last active timestamp for auto-logout
How the Application Works

The session stores not just the user_id but also a second flag (pin_verified = true) that is set only after the user enters their transaction PIN. This prevents any transfer from completing without this secondary check. Every transfer involves two database writes — a debit transaction for the source account and a credit transaction for the destination — which should be wrapped in a way that ensures both succeed or neither does, simulating atomicity.

Key Database Relationships
  • Users can have multiple accounts (savings, current), each with an account_type and currency.
  • Each transaction references from_account_id and to_account_id, with a type (transfer, deposit, withdrawal) and a reference number.
  • Beneficiaries link a user to frequently transferred-to accounts outside their ownership, reducing re-entry of account numbers.
What Students Learn

Multi-step session authentication flows (password → PIN → action), the critical importance of atomic double-entry for financial transactions, and how to implement session-based inactivity timeouts — all patterns used in real banking software.

Clinic Appointment Scheduling System
Doctors · Slots · Patients · Reminders
Intermediate

A focused appointment booking system for a clinic where patients select a doctor, view their available time slots for the coming days, book a slot, and receive a confirmation — while doctors control their availability calendar.

Core Concepts Used
Time slot gridAvailability matrixConflict checkingDoctor schedulesStatus flow
Tables
doctors, patients, specializations, availability_slots, appointments, appointment_types
Sessions Used For
Patient login, selected doctor and date held in session through two-step booking process
How the Application Works

Doctors define their weekly working hours by inserting availability_slot records (e.g., Monday 09:00–12:00, slot_duration 30 minutes). When a patient views a doctor's booking calendar, PHP generates the list of potential slots from those templates, then queries the appointments table to mark which ones are already taken. The patient picks a free slot; the selected date and time are saved in the session before the final confirmation page.

Key Database Relationships
  • Doctors link to specializations, which allows patients to search by medical specialty rather than a specific name.
  • Availability slots belong to a doctor and define day-of-week, start time, end time, and slot_duration — from which PHP generates the time grid.
  • Appointments reference the doctor, patient, appointment_type, and the specific slot datetime, with a status column for the lifecycle.
What Students Learn

The difference between template/availability data and actual booking records, slot-generation logic in PHP using loops and time arithmetic, and how to efficiently display a conflict-aware calendar grid using a single JOIN query.

Multi-Vendor Marketplace
Vendors · Products · Orders · Commissions
Advanced

A platform marketplace like Jumia or Etsy where multiple vendors each maintain their own product catalogue, receive orders routed to them, and the platform automatically calculates commission splits — with three-level session roles: buyer, vendor, and superadmin.

Core Concepts Used
Multi-tenancyCommission splitsOrder routingVendor dashboard3-role sessions
Tables
users, vendors, products, orders, order_items, commissions, vendor_payouts
Sessions Used For
Three-role access control (buyer/vendor/admin), vendor context, shared cart across multiple vendors
How the Application Works

A buyer can add products from multiple vendors into one cart (session-stored). On checkout, the single order is split: each order_item knows which vendor it belongs to (via the product's vendor_id), and the commissions table records what percentage of each item's price goes to the platform versus the vendor. Vendors log in with the "vendor" session role and see only their own orders and products. The superadmin sees aggregated sales across all vendors and can trigger payouts to vendor bank accounts by updating the vendor_payouts table.

Key Database Relationships
  • Vendors are linked to a user account but exist in their own table with store name, logo, and commission_rate.
  • Products link to vendors, with all data scoping through vendor_id — ensuring a vendor can never access another's data even if they manipulate form parameters.
  • The commissions table records the platform_amount and vendor_amount for each order_item, computed at checkout time rather than recalculated later.
  • Vendor payouts link to a vendor and mark which commission records have been settled.
What Students Learn

Multi-tenancy architecture (every query filtered by vendor_id), the complexity of splitting a single customer transaction into multiple vendor-specific records, preventing horizontal privilege escalation (a vendor accessing another vendor's data), and commission/financial split logic — one of the most sophisticated real-world patterns in marketplace development.