VU LIVE
📢 Browse Moaaz & Arslan Papers — CS, MTH, ENG, MGT and more — Free study resources
All Pages Linked
Official Virtual Ustaad Academic Portal

CS619 Hotel and Tour Reservation System Project — Complete Source Code with SRS, ERD and Viva Q&A

Virtual University of Pakistan — Verified Study Resources & Student Support

The CS619 Hotel and Tour Reservation System is one of the most popular final year projects at Virtual University, and this guide builds it completely — in PHP and MySQL — so you can both learn and submit it. You start with the SRS: who uses the system, what it must do, and the rules (room price is nights times price per night, a room can never be double-booked, tour price is guests times price per person). Then you design the database with an ERD, write the code module by module with line-by-line explanations, test it with 20 test cases, and finish with viva questions and answers. The complete working code is included: login, dashboard, hotel and room management, tour packages, search, booking, cancellation and reviews. Follow the guide in order and you will have a working project and the understanding to defend it in the viva.

Hotel / Tour Reservation System — Learn + Build Guide

Course: CS619 Final Project, Virtual University of Pakistan Project: Hotel / Tour Reservation System (Top Project #9 — "E-HOTEL": An Online Hotel Management System, Earlier list; Online Tour and Hotel Reservation System for Pakistan, Spring 2025; a Fall 2026 YouTube demo teaches "Hotel Room Booking System") Stack: PHP + MySQL (XAMPP), built in plain PHP + MySQL. The official specification states PHP (Laravel Framework), MySQL, ASP.NET, C#, SQL Server (Spring 2025). This build uses plain PHP + MySQL in the same verifiable style as the Library Management System pilot: no framework, so every line is the student's own code and can be explained in the viva. The same design maps to Laravel — the guide explains the mapping in Section 5.1. How to use this guide: build the project in the order of this guide — SRS, then Design, then Coding, then Testing, then Viva preparation. Every section first explains the idea in plain English, then shows the work. The complete code is in the files beside this guide; the Coding section explains each module and shows the important code with line-by-line notes.


1. Project overview — what you are building

A hotel takes bookings by phone and in a register: which guest, which room, which dates, and how much they paid. That is slow, rooms get double-booked by mistake, and nobody knows which rooms are free next week. This system replaces the register with a web application where customers search hotels by city and date, book a room or a tour package, and the system itself makes sure a room is never booked twice for the same dates.

What the system does

  • The admin (hotel manager) adds hotels, rooms and tour packages, sees every booking, today's check-ins and the total revenue.
  • A customer searches hotels by city and check-in / check-out dates, sees which rooms are free for those dates, books a room, books a tour package, views their own bookings, cancels a booking, and reviews a hotel they stayed in.
  • The system itself works out prices (room: nights × price per night; tour: guests × price per person), refuses overlapping room bookings, refuses tour bookings when no seats are left, and frees a room when its booking is cancelled.

Who uses it

User What they can do
Admin (hotel manager) Everything: hotels, rooms, tour packages, all bookings, dashboard, cancel any booking
Customer (guest) Search hotels and tours, book rooms and tours, view and cancel own bookings, write reviews

Scope — what is in, and what is not

In scope: login with two roles, hotel/room/tour management, search by city and date with availability, room booking with overlap protection, tour booking with seat limits, booking list and detail, cancellation, customer "My Bookings", reviews, dashboard with counts and revenue.

Out of scope: online payment (bookings are confirmed without payment), email confirmation, a customer "change password" page, and a room availability calendar view. These are listed as future improvements at the end of this guide. Saying clearly what you did NOT build — and why — is something viva examiners respect.


2. What you will learn (read this before you start coding)

You do not need to know everything below in advance. Learn each item when you reach the module that uses it.

Topic Where you use it
HTML forms (GET vs POST) Every page: login, add hotel, search, booking
PHP basics: variables, if/else, loops, functions Every file
PHP sessions ($_SESSION) Login: remembering who is logged in
MySQL: tables, primary keys, foreign keys schema.sql
PDO prepared statements (? placeholders) Every database query — this is how SQL injection is stopped
password_hash() / password_verify() Login
SQL transactions (beginTransaction / commit / rollBack) Room booking and tour booking — checks and insert that must happen together
FOR UPDATE row locks Booking — stops two customers booking the same room at the same moment
Date overlap logic (check_in < new_check_out AND check_out > new_check_in) Room availability — the heart of the system
SQL joins (bookings + hotels + rooms + tours) Dashboard, booking list, My Bookings
DATE functions (CURDATE(), DATEDIFF()) Nights, today's check-ins, completed stays

Suggested order of work (about 4–6 weeks for one student)

  1. Week 1: install XAMPP, create the database, write the SRS (Section 3).
  2. Week 2: design the database and draw the ERD (Section 4).
  3. Weeks 3–4: write the code module by module (Section 5).
  4. Week 5: run the test cases (Section 6) and fix the bugs they find.
  5. Week 6: prepare the final report and practise the viva questions (Section 7).

3. SRS — Software Requirements Specification

This section is written so you can copy it into your SRS document (with your own project details) — it follows the sections VU expects in an SRS: purpose, scope, actors, functional requirements, non-functional requirements, and use cases.

3.1 Purpose

To build a web-based Hotel / Tour Reservation System that automates hotel room booking and tour package booking for hotels and tour operators in Pakistan, replacing phone calls and paper registers with a system that shows live availability, prevents double booking, and keeps a complete record of every booking.

3.2 Scope

The system covers the daily work of a small hotel and tour business: hotel, room and tour package management; searching hotels by city and date; booking rooms and tours; viewing, cancelling and reviewing bookings; and reports (dashboard counts, today's check-ins, revenue, booking history). It does not cover online payment, email confirmation, or a calendar view of availability.

3.3 Actors

  • Admin (hotel manager): manages the whole system. There is one admin account to start with; more admin accounts can be added directly in the database.
  • Customer (guest): a registered user. Customers search hotels and tours, book rooms and tours, view and cancel their own bookings, and write reviews. Customers cannot change hotels, rooms or tours, and cannot see other customers' bookings.

3.4 Functional requirements

ID Requirement
FR1 The system shall let a user log in with a username and password. Wrong credentials shall be rejected with one general error message.
FR2 The system shall show different menus for admin and customer after login.
FR3 The admin shall add a hotel with name, city, address, star rating (1–5), description and contact number.
FR4 The admin shall edit and delete hotels. A hotel with booking history shall not be deletable.
FR5 The admin shall add a room to a hotel with room number, type, capacity, price per night and availability. The room number shall be unique inside one hotel.
FR6 The admin shall edit and delete rooms. A room with booking history shall not be deletable.
FR7 The admin shall add, edit and delete tour packages with title, destination, duration, price per person, maximum seats, start date and end date. End date shall not be before start date.
FR8 Any logged-in user shall search hotels by city, and rooms by city with check-in and check-out dates.
FR9 The search shall show, for each room, whether it is free for the chosen dates. A room with a confirmed booking overlapping those dates shall be shown as booked.
FR10 A customer shall book a room for check-in and check-out dates. Check-out shall be after check-in and check-in shall not be in the past. Guests shall not exceed the room's capacity.
FR11 The system shall refuse a room booking when a confirmed booking for the same room overlaps the chosen dates. Two bookings overlap when existing check-in < new check-out AND existing check-out > new check-in. A booking that ends on the day the new one starts does NOT overlap.
FR12 The system shall calculate the room price as nights × price per night, where nights = check-out minus check-in. The price shall be calculated by the system, never typed by the user.
FR13 A customer shall book a tour package for a departure date inside the package's offered dates. Guests × price per person shall be the total. The booking shall be refused when the guests would exceed the seats left on that departure date.
FR14 The admin dashboard shall show: total hotels, rooms, tour packages, confirmed bookings, confirmed revenue, and customers; plus today's check-ins and the 10 most recent bookings.
FR15 The admin shall see the full booking list, filterable by All / Room / Tour / Confirmed / Cancelled, and the detail of any booking.
FR16 A customer shall see only their own bookings, with total spent on confirmed bookings, and a "completed" mark on a room stay whose check-out date has passed.
FR17 A customer shall cancel their own booking and the admin shall cancel any booking. Cancelling shall set the status to 'cancelled' (not delete the row) and shall free the room for those dates.
FR18 A customer shall review a hotel they have a confirmed room booking for, once per booking, with a rating of 1–5 stars and an optional comment. The hotel page shall show the average rating.

3.5 Non-functional requirements

ID Requirement
NFR1 Security: passwords shall be stored as hashes, never as plain text. All database queries shall use prepared statements. Pages shall check login on every request.
NFR2 Usability: every action shall show a success or error message. Forms shall keep the typed values when validation fails.
NFR3 Correctness: a room shall never be double-booked, even when two customers book at the same moment (row lock + transaction). Total prices shall always be calculated by the system.
NFR4 Performance: the search and the dashboard shall answer in under 2 seconds with the sample data.
NFR5 Portability: the system shall run on XAMPP (Apache + MySQL) on Windows without extra software.

3.6 Use cases

                    +-----------------------------------+
                    |  Hotel / Tour Reservation System  |
                    |                                   |
   Admin ---------->|  Login                            |
     |              |  Manage Hotels, Rooms, Tours      |
     |              |  View Dashboard & All Bookings    |
     |              |  Cancel Any Booking               |
                    |                                   |
   Customer ------->|  Login                            |
                    |  Search Hotels by City & Date     |
                    |  Book Room / Book Tour            |
                    |  View My Bookings                 |
                    |  Cancel Own Booking               |
                    |  Write Review                     |
                    +-----------------------------------+
Use case Actor Main flow
Login Admin, Customer Enter username + password → system checks credentials → opens the right home page
Add Hotel Admin Fill the hotel form → system validates → hotel appears in the list
Add Room Admin Pick a hotel, fill the room form → system checks the room number is new in that hotel → room appears
Add Tour Admin Fill the tour form → system checks the dates → tour appears
Search Hotels Admin, Customer Pick a city and dates → system lists rooms and marks each as free or booked for those dates
Book Room Customer Pick a room and dates → system runs the 4 checks → booking confirmed with the total price
Book Tour Customer Pick a tour, date and guests → system checks seats → booking confirmed with the total price
Cancel Booking Admin, Customer Open a confirmed booking → confirm cancellation → room is free for those dates again
Write Review Customer Pick one of their confirmed stays at a hotel → give 1–5 stars → review appears on the hotel page
View Dashboard Admin System shows counts, revenue, today's check-ins and recent bookings
View My Bookings Customer System shows only the customer's own bookings, with total spent

4. Design

4.1 Architecture

  Customer / Admin browser
        |
        |  HTTP (forms, links)
        v
  Apache web server (XAMPP)
        |
        |  PHP files (this project)
        v
  MySQL database (hotel_db)

There is no framework and no JavaScript framework. That is a deliberate choice for a final-year project: every line of code is yours, you can explain all of it in the viva, and nothing is hidden inside a library.

Request flow for every page: config.php (session + database connection) → header.php (login check + menu) → page logic → footer.php.

4.2 ERD — Entity Relationship Diagram

  users (1) ───< bookings (N) >─── (1) rooms
  users (1) ───< bookings (N) >─── (1) tour_packages
  users (1) ───< reviews  (N) >─── (1) hotels
  hotels (1) ───< rooms (N)
  hotels (1) ───< bookings (N)

  +----------------+      +----------------+
  | users          |      | hotels         |
  | id (PK)        |      | id (PK)        |
  | name           |      | name           |
  | username       |      | city           |
  | email          |      | address        |
  | password_hash  |      | star_rating    |
  | role           |      | description    |
  | phone, address |      | contact_no     |
  | status         |      +-------+--------+
  +-------+--------+              | 1
          |                       |
          | 1                     * 
      +---v------------+      +----v---------+
      | bookings       |      | rooms        |
      | id (PK)        |      | id (PK)      |
      | user_id (FK) --+      | hotel_id FK -+
      | booking_type   |      | room_number  |
      | room_id (FK) --+      | room_type    |
      | tour_package_  |      | capacity     |
      |   id (FK)      |      | price_per_   |
      | hotel_id (FK)  |      |   night      |
      | check_in       |      | is_available |
      | check_out      |      +--------------+
      | guests         |
      | total_price    |      +----------------+
      | status         |      | tour_packages  |
      +-------+--------+      | id (PK)        |
              |               | title          |
              | 1             | destination    |
              |               | duration_days  |
      +-------v--------+      | price_per_     |
      | reviews        |      |   person       |
      | id (PK)        |      | max_seats      |
      | hotel_id (FK)  |      | start_date     |
      | user_id (FK)   |      | end_date       |
      | booking_id FK  |      | description    |
      | rating         |      +-------+--------+
      | comment        |              ^ 1
      +----------------+              |
                                      |
              bookings.tour_package_id +

Relationships (read "1" as "one", "N" as "many"):

Relationship Meaning
users 1 — N bookings (user_id) One customer can make many bookings; each booking belongs to one customer.
hotels 1 — N rooms (hotel_id) One hotel has many rooms; each room belongs to one hotel.
rooms 1 — N bookings (room_id) One room can be booked many times over the year; each room booking is for one room.
tour_packages 1 — N bookings (tour_package_id) One tour package can be booked many times; each tour booking is for one package.
hotels 1 — N bookings (hotel_id) One hotel appears in many room bookings; each room booking names its hotel (so the dashboard and reports do not need a join through rooms).
users 1 — N reviews (user_id) One customer can write many reviews; each review is by one customer.
hotels 1 — N reviews (hotel_id) One hotel can have many reviews; each review is about one hotel.
bookings 1 — 1 reviews (booking_id) One booking can have at most one review (UNIQUE on booking_id); each review is tied to the stay it is about.

4.3 Database design, table by table

users — everyone who can log in. role is admin or customer. password_hash holds a bcrypt hash, never the password itself. status is active or suspended; only the admin can change it (by editing the database — there is no member-management page in this build, which is listed as a future improvement).

hotels — one row per hotel. city is the search key. star_rating is 1 to 5, enforced by a database CHECK. contact_no is the hotel's phone number.

rooms — one row per physical room in a hotel (not per room type: room 101 and room 102 are separate rows, even when both are "Deluxe"). room_number is unique inside one hotel — UNIQUE (hotel_id, room_number) — so two hotels can both have a room 101, but one hotel cannot have two room 101s. price_per_night is in Rupees. is_available = 0 means the room is under maintenance and cannot be booked at all; this is different from being booked for some dates. Deleting a hotel deletes its rooms (ON DELETE CASCADE), because a room cannot exist without its hotel.

tour_packages — one row per tour package. destination is the place the tour visits (Hunza, Swat, Murree...). max_seats is the seats on one departure. start_date / end_date are the dates the package is offered. The CHECK end_date >= start_date stops a package that ends before it starts.

bookings — one row per booking, of two kinds. booking_type is room or tour. For a room booking, room_id is set, tour_package_id is NULL, and check_in / check_out are the stay dates. For a tour booking, tour_package_id is set, room_id is NULL, check_in is the departure date and check_out is NULL. total_price is always worked out by the code, never typed by the user. status is confirmed or cancelled. One table for both kinds keeps the booking list, the dashboard and "My Bookings" simple: one query shows everything.

reviews — one row per review. rating is 1 to 5 (CHECK). booking_id is UNIQUE, so one booking can be reviewed at most once. hotel_id is stored directly so the hotel page can list its reviews without joining through bookings.

Why "completed" is NOT a status. A tempting design is a third status, completed. The problem: a stay becomes completed at check-out time, but nobody updates the database at check-out time — so the stored status would be wrong until someone runs an update. Instead this system computes completed: a room booking is completed when status = 'confirmed' AND check_out < today. The answer is always correct, with no daily job. This is a good example to quote in the viva when asked about a design decision. (The Library pilot does the same thing for "overdue".)

Why "seats left" is NOT stored. The same reasoning: seats left changes with every booking and every cancellation. Storing it would mean updating it in two places and risking a wrong number. Instead it is computed: max_seats − SUM(guests of confirmed bookings for that tour on that date). Always correct, no extra updates.

4.4 UI flow (page map)

  index.php (Login)
      |
      +-- admin --> dashboard.php
      |               |-- hotels.php <--> hotel_add / hotel_edit / hotel_delete
      |               |-- rooms.php  <--> room_add / room_edit / room_delete
      |               |-- tours.php  <--> tour_add / tour_edit / tour_delete
      |               +-- bookings.php --> booking_detail.php
      |                                      +-- booking_cancel.php
      |
      +-- customer -> search.php --> book_room.php
                    |-- tours.php --> book_tour.php
                    |-- hotel_detail.php (rooms + reviews + review form)
                    +-- my_bookings.php --> booking_detail.php
                                              +-- booking_cancel.php

4.5 Design decisions worth defending in the viva

  1. PDO prepared statements everywhere. User input is never pasted into SQL. This stops SQL injection completely.
  2. Transactions + FOR UPDATE for booking. Booking a room is a check and an insert that must happen together. The row lock makes a second customer wait; when they continue, they see the first booking and are refused. Without the lock, both could succeed and the room would be double-booked.
  3. One bookings table for rooms and tours. The two kinds share guest, dates, price and status, so one table keeps the list, dashboard and cancellation code in one place instead of two.
  4. Computed "completed" and computed "seats left" (see 4.3) — no stale data, no daily job.
  5. Cancellation is a status, not a delete. The history stays, and the room becomes free because the overlap check only counts confirmed bookings.
  6. No framework. Every line is the student's own code and can be explained in the viva.
  7. Laravel mapping. The official specification names Laravel. This build is plain PHP so it can be verified without installing a framework, but the design maps one-to-one: hotels, rooms, tour_packages, bookings, reviews become Eloquent models; book_room.php becomes a controller method with the same overlap query inside DB::transaction(); config.php helpers become a base controller and middleware (auth, admin); the HTML forms become Blade views. A student who understands this code can move it to Laravel in a day.

5. Coding — module by module

Each module is explained in plain English first, then the important code is shown with line-by-line notes. The full code is in the files beside this guide — read the module, then open its file and follow along.

5.1 Module 1 — Configuration and database connection (config.php)

What it does: every page needs two things — a session (to remember who is logged in) and a database connection. config.php provides both, plus small helper functions, so no page repeats that setup.

session_start();                       // (1)

define('DB_HOST', 'localhost');        // (2)
define('DB_NAME', 'hotel_db');
define('DB_USER', 'root');
define('DB_PASS', '');                 // XAMPP default: root has no password

define('MAX_GUESTS_PER_ROOM', 6);      // (3)

$pdo = new PDO(                        // (4)
    'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
    DB_USER, DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
     PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);

Line by line: (1) session_start() must run before any HTML is printed, or PHP shows a "headers already sent" error. (2) The database settings are constants, so they are written once and used everywhere. (3) The booking rules are also constants — changing a rule means changing one line, not searching every file. (4) PDO is PHP's database layer. ERRMODE_EXCEPTION means a database error throws an exception instead of failing silently. FETCH_ASSOC means rows come back as ['name' => '...', 'city' => '...'] arrays.

Helpers in the same file: e() escapes text before printing it (stops cross-site scripting); redirect() sends the browser elsewhere; flash() / showFlash() carry a one-time message to the next page; requireLogin() and requireAdmin() guard pages; nightsBetween() returns whole nights between two dates (used for the room price); money() formats a price as "Rs. 25,000".

5.2 Module 2 — Login and sessions (index.php, logout.php)

What it does: checks a username and password, then remembers the user in the session until logout. Identical in shape to the Library pilot's login, with the roles changed to admin / customer.

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
$stmt->execute([$username]);
$user = $stmt->fetch();

if ($user && $user['status'] === 'active'
    && password_verify($password, $user['password_hash'])) {
    session_regenerate_id(true);
    $_SESSION['user_id']   = (int) $user['id'];
    $_SESSION['role']      = $user['role'];
    // ... then redirect to dashboard (admin) or search (customer)
}

Line by line: the ? in the query is a placeholder — the username is sent separately, so even a username like ' OR '1'='1 cannot change the SQL (this is the SQL-injection defence). password_verify() compares the typed password with the stored hash; the real password is never in the database. session_regenerate_id(true) gives the user a fresh session id after login, so an old session id cannot be reused. $_SESSION is a server-side array that survives from page to page — that is how the system "remembers" the login. The error message is always the same ("Invalid username or password") whether the username or the password was wrong, so an attacker cannot learn which usernames exist.

5.3 Module 3 — Hotels (hotels.php, hotel_add.php, hotel_edit.php, hotel_delete.php)

What it does: list and search hotels; add, edit and delete them (admin only).

The list also shows each hotel's average rating, with a subquery (from hotels.php):

SELECT h.*,
       (SELECT AVG(rating) FROM reviews WHERE hotel_id = h.id) AS avg_rating,
       (SELECT COUNT(*) FROM reviews WHERE hotel_id = h.id) AS review_count
  FROM hotels h WHERE h.city LIKE ? ORDER BY h.name ASC

The subqueries run once per hotel row; with a small hotel list that is fine, and it keeps the query readable for a student. (For a very large list, a LEFT JOIN with GROUP BY would be faster — see the future improvements.)

Delete (from hotel_delete.php): two rules. First, deletion needs a confirmation page with a POST form, so a plain link can never delete anything. Second, a hotel with any booking history cannot be deleted, because the bookings table references it. Its rooms would be deleted by ON DELETE CASCADE, but the booking history must stay.

5.4 Module 4 — Rooms (rooms.php, room_add.php, room_edit.php, room_delete.php)

What it does: list rooms (filterable by hotel), add, edit and delete them (admin only). Customers see the same list with a "Book" link.

The room-number rule (from room_add.php): the database enforces UNIQUE (hotel_id, room_number), and the code catches the error:

try {
    $stmt = $pdo->prepare(
        'INSERT INTO rooms (hotel_id, room_number, room_type, capacity,
                            price_per_night, is_available)
         VALUES (?, ?, ?, ?, ?, ?)'
    );
    $stmt->execute([...]);
} catch (PDOException $e) {
    // Error 23000 = duplicate key: this hotel already has this room number.
    $error = ($e->getCode() === '23000')
        ? 'This hotel already has a room with that number.'
        : 'Could not add the room. ' . $e->getMessage();
}

23000 is the SQLSTATE code for an integrity-constraint violation — in practice, the duplicate room number. Showing a friendly message instead of the database error is part of NFR2 (usability).

Delete (from room_delete.php): like hotels, a room with booking history cannot be deleted. To hide a room without losing its history, the admin unchecks "Available for booking" instead — the room then shows as "Under maintenance" and cannot be booked.

5.5 Module 5 — Tour packages (tours.php, tour_add.php, tour_edit.php, tour_delete.php)

What it does: list tour packages with seats left, add, edit and delete them (admin only).

"Seats left" is computed, not stored (from tours.php):

SELECT t.*,
       COALESCE(SUM(CASE WHEN b.status = 'confirmed' THEN b.guests ELSE 0 END), 0)
           AS seats_booked
  FROM tour_packages t
 LEFT JOIN bookings b ON b.tour_package_id = t.id AND b.booking_type = 'tour'
 GROUP BY t.id

CASE WHEN ... THEN b.guests ELSE 0 END counts only confirmed bookings — cancelled bookings give their seats back automatically. COALESCE(..., 0) turns NULL (a tour with no bookings at all) into 0. Seats left = max_seats − seats_booked, worked out in the PHP loop.

Edit (from tour_edit.php): the admin cannot shrink max_seats below the seats already booked, because that would leave the tour overbooked. The code counts the confirmed guests first and refuses with a clear message.

5.6 Module 6 — Search by city and date (search.php)

What it does: the customer's home page. Pick a city and dates, and the page lists every available room in that city, marking each one as free or booked for those dates.

The availability check is one EXISTS subquery:

SELECT h.name AS hotel_name, h.city,
       r.id AS room_id, r.room_number, r.room_type, r.capacity,
       r.price_per_night,
       EXISTS (
           SELECT 1 FROM bookings b
            WHERE b.room_id = r.id
              AND b.booking_type = 'room'
              AND b.status = 'confirmed'
              AND b.check_in < ? AND b.check_out > ?
       ) AS is_booked
  FROM hotels h
  JOIN rooms r ON r.hotel_id = h.id
 WHERE r.is_available = 1 AND h.city LIKE ?

The two ? are the new check-out and the new check-in, in that order: an existing booking overlaps when existing check-in < new check-out AND existing check-out > new check-in. EXISTS returns 1 as soon as it finds one overlapping booking, so it is fast. Booked rooms are still listed (with a "Booked for these dates" badge) instead of being hidden, so the customer can see why a hotel has no free rooms.

5.7 Module 7 — Book a room (book_room.php) — the most important module

What it does: books a room for a customer, after four checks, inside a transaction.

$pdo->beginTransaction();                              // (1)

// Lock the room row: a second customer booking the same room at the
// same moment waits here until this transaction finishes.
$stmt = $pdo->prepare('SELECT * FROM rooms WHERE id = ? FOR UPDATE');
$stmt->execute([$roomId]);                             // (2)

// Overlap check — the heart of the system. Only confirmed bookings
// count; cancelled ones do not block the room.
$stmt = $pdo->prepare(
    "SELECT COUNT(*) FROM bookings
      WHERE room_id = ? AND booking_type = 'room' AND status = 'confirmed'
        AND check_in < ? AND check_out > ?"
);
$stmt->execute([$roomId, $checkOut, $checkIn]);        // (3)
if ((int) $stmt->fetchColumn() > 0) {
    throw new Exception('Sorry, this room is already booked for those dates.');
}

// Price is computed here, never from user input.
$nights = nightsBetween($checkIn, $checkOut);          // (4)
$totalPrice = $nights * (float) $room['price_per_night'];

$stmt = $pdo->prepare(
    "INSERT INTO bookings (user_id, booking_type, room_id, tour_package_id,
                           hotel_id, check_in, check_out, guests,
                           total_price, status)
     VALUES (?, 'room', ?, NULL, ?, ?, ?, ?, ?, 'confirmed')"
);
$stmt->execute([...]);

$pdo->commit();                                         // (5)

Line by line: (1) beginTransaction() starts the transaction — from here, nothing is saved until commit(). (2) FOR UPDATE locks the room row: if another customer is booking the same room at the same moment, they wait until this transaction finishes, then see the new booking and are refused. (3) The overlap test uses the same rule as the search: existing check-in < new check-out AND existing check-out > new check-in. A booking that ends on the day the new one starts does NOT overlap — the room is free that morning — and a cancelled booking never blocks the room, because only status = 'confirmed' is counted. (4) The price is nights × price per night, computed from the room row in the database, so a customer cannot change the price by editing the form. (5) commit() saves the booking. If any check throws an exception, the catch block calls rollBack() and nothing is saved.

The four checks, in order, before the transaction: the room exists and is available (not under maintenance); the dates are valid (check-out after check-in, check-in not in the past); the guests fit the room's capacity; no confirmed booking overlaps.

5.8 Module 8 — Book a tour (book_tour.php)

What it does: books seats on a tour package for a departure date.

The seat check, inside a transaction with the tour row locked:

$pdo->beginTransaction();

$stmt = $pdo->prepare('SELECT * FROM tour_packages WHERE id = ? FOR UPDATE');
$stmt->execute([$tourId]);

// Seats already booked on THIS departure date only.
$stmt = $pdo->prepare(
    "SELECT COALESCE(SUM(guests), 0) FROM bookings
      WHERE tour_package_id = ? AND booking_type = 'tour'
        AND status = 'confirmed' AND check_in = ?"
);
$stmt->execute([$tourId, $departureDate]);
$seatsLeft = (int) $tour['max_seats'] - (int) $stmt->fetchColumn();

if ($guests > $seatsLeft) {
    throw new Exception('Only ' . $seatsLeft . ' seat(s) left on ' . $departureDate . '.');
}

$totalPrice = $guests * (float) $tour['price_per_person'];
// ... insert the booking, then commit

Note that seats are counted per departure date (check_in = ?), not per tour: the same package runs on many dates, and a full departure on 25 November must not block a departure on 10 December. The departure date must also fall inside the package's offered dates (start_date to end_date) and must not be in the past.

5.9 Module 9 — Bookings, cancellation and My Bookings

bookings.php (admin): lists every booking, newest first, with a filter. The filter value is checked against an allowed list (all, room, tour, confirmed, cancelled) before it reaches the SQL — a made-up filter value can never change the query. This is the same technique the Library pilot uses for its issue-history filter.

booking_detail.php: shows one booking in full, with the price breakdown. Admins can open any booking. A customer can open only their own — the user id comes from the session, never from the URL, so a customer cannot view another customer's booking by changing the address. It also shows a "Write a review" link for a confirmed room booking that has not been reviewed yet.

booking_cancel.php: sets status = 'cancelled' — it does not delete the row. That is what frees the room: the overlap check only counts confirmed bookings, so after cancellation the same dates can be booked again. A customer can cancel only their own booking; an admin can cancel any booking. Cancelling an already-cancelled booking is refused with a clear message.

my_bookings.php: the customer's own bookings only. The customer id comes from the session, never from the URL. It shows the total spent on confirmed bookings, and marks a room stay as "completed" when its check-out date has passed (computed, not stored — see Section 4.3).

5.10 Module 10 — Dashboard (dashboard.php)

What it does: turns the stored rows into answers for the manager.

  • Counts are single COUNT(*) queries — cheap and fast.
  • Revenue is SUM(total_price) over confirmed bookings only.
  • Today's check-ins are WHERE booking_type = 'room' AND status = 'confirmed' AND check_in = CURDATE().
  • Recent bookings join bookings with users, hotels, rooms and tours in one query, newest first, limited to 10.

5.11 Module 11 — Hotel detail and reviews (hotel_detail.php)

What it does: shows one hotel, its rooms, its reviews with the average rating, and the review form.

The review rules, enforced by the code and the database together:

  • The customer must have a confirmed room booking at this hotel, and that booking must not have been reviewed yet. The form only lists bookings that pass both tests, and the POST handler re-checks them against the database (a form can always be tampered with, so the server must never trust it).
  • Rating must be 1–5, enforced by the form, the code, and a database CHECK.
  • One booking, one review: UNIQUE (booking_id) in the database makes a second review for the same stay impossible even if the code check were bypassed.

6. Testing — test cases to run before submission

Run every case below against the working system and record Pass/Fail. A failed case is not a disaster — it is what testing is for; fix the bug, then run the case again.

ID Test Steps Expected result
TC-1 Login (admin) Log in as admin / admin123 Dashboard opens, admin menu shown
TC-2 Login (customer) Log in as customer / customer123 Search page opens, customer menu shown (no Dashboard link)
TC-3 Wrong password Log in as admin with a wrong password "Invalid username or password", still on login page
TC-4 Page guard Open dashboard.php without logging in Sent back to the login page
TC-5 Customer guard As a customer, open bookings.php directly Sent back to the dashboard with an error
TC-6 Add hotel Add a hotel in Lahore Hotel appears in the list
TC-7 Add room Add room 103 to a hotel, Double, Rs. 15,000 Room appears with price Rs. 15,000
TC-8 Duplicate room number Add room 101 again to the same hotel "This hotel already has a room with that number"
TC-9 Search Search city "Lahore" with dates Lahore rooms listed; booked rooms marked "Booked for these dates"
TC-10 Book a room As customer, book room 102 (PC Lahore) for 2 nights "Room booked!" Total = 2 × Rs. 25,000 = Rs. 50,000
TC-11 Double booking Book the same room for overlapping dates (e.g. one day later) Refused: "already booked for those dates"
TC-12 Back-to-back booking Book the same room starting on the old check-out day Accepted — the room is free that morning
TC-13 Sample booking protected Book room 101 (PC Lahore) for 21–23 Nov 2026 Refused — the sample booking covers 20–22 Nov
TC-14 Past dates Book a room with check-in yesterday Refused: "cannot be in the past"
TC-15 Too many guests Book a Single room (capacity 1) for 3 guests Refused: room holds at most 1 guest
TC-16 Book a tour Book 2 seats on Hunza Valley Explorer for 25 Nov 2026 "Tour booked!" Total = 2 × Rs. 45,000 = Rs. 90,000
TC-17 Over-seat tour booking Book 19 seats on the same tour and date (only 16 left after TC-16 + sample) Refused: "Only 16 seat(s) left"
TC-18 Cancel frees the room Cancel the TC-10 booking, then book the same room and dates again Second booking accepted
TC-19 Cancel twice Cancel the same booking a second time Refused: "already cancelled"
TC-20 My Bookings privacy As Ayesha, check My Bookings Only Ayesha's bookings appear, never Ali's

Verified results (this build, 7 Nov 2026): all 26 PHP files pass php -l; schema imports into MariaDB 10.11 with all 6 tables and the sample data; admin/admin123 reaches the dashboard; customer/customer123 reaches the search page; wrong password is rejected; unauthenticated dashboard redirects to login; room booking for 2 nights totals Rs. 50,000; overlapping booking refused; back-to-back booking accepted; sample booking protected; tour booking totals Rs. 90,000; 19-seat booking refused with "Only 16 seat(s) left"; cancelling frees the room and the same dates can be booked again; customer cannot open the admin booking list. Test bookings were deleted afterwards, leaving the database in its clean sample state.

How to make a stay "completed" for testing: book a room with dates in the past is not allowed, so instead change a booking's check_out to yesterday in phpMyAdmin (or in the MySQL command line) and open My Bookings — the stay shows the "completed" badge.


7. Viva Q&A — questions the examiner is likely to ask

Q1. What does your project do? It automates hotel and tour booking: the admin manages hotels, rooms and tour packages; customers search by city and date, book rooms and tours, cancel bookings and write reviews. The system calculates prices and stops double booking.

Q2. Which technologies did you use, and why? PHP and MySQL on XAMPP, in plain PHP with no framework — the stack in the official specification is PHP (Laravel), MySQL, ASP.NET, C#, SQL Server. Plain PHP was chosen so every line is mine and I can explain it in the viva, and the same design maps to Laravel (Section 4.5).

Q3. Show me your database design. Why six tables? users (login), hotels, rooms (one row per physical room), tour_packages, bookings (one row per room or tour booking), and reviews. Six tables is enough because a booking is the only thing that connects a customer to a room or a tour, and a review is tied to one booking. The ERD is in Section 4.2.

Q4. What is a foreign key? Give an example from your project. A column that must match a primary key in another table. bookings.room_id must be an id from rooms — the database refuses a booking for a room that does not exist.

Q5. How do you stop double booking? Two bookings for the same room overlap when existing check-in < new check-out AND existing check-out > new check-in. The booking code runs this check inside a transaction while the room row is locked with FOR UPDATE, so two customers booking at the same moment cannot both succeed. Cancelled bookings do not count, so cancelling frees the room.

Q6. Why does a booking that ends on the day the new one starts not overlap? Because the old guest checks out in the morning and the new guest checks in later that day. The test is strict: check_in < new check-out AND check_out > new check-in. When the old check-out equals the new check-in, the second half is false, so there is no overlap. Test case TC-12 proves it.

Q7. How do you stop SQL injection? Every query uses PDO prepared statements with ? placeholders. User input is sent as data, never pasted into the SQL string, so input like ' OR '1'='1 is treated as a plain value, not as SQL.

Q8. How are passwords stored? With password_hash(), which makes a bcrypt hash. The plain password is never stored. Login checks with password_verify().

Q9. How is the room price calculated? Nights × price per night. Nights = check-out minus check-in, worked out by nightsBetween() in config.php. The price comes from the room row in the database, never from the form, so a customer cannot change it. Tour price is guests × price per person, the same way.

Q10. What is a transaction, and where did you use one? A group of database changes that succeed together or fail together. Booking a room is a check plus an insert, so they run in one transaction; if the overlap check fails, nothing is saved. The same applies to tour booking (seat check plus insert).

Q11. Two customers book the same room at the same moment. What happens? The first transaction locks the room row with FOR UPDATE. The second waits, then sees the first booking in the overlap check and is refused. Without the lock, both could pass the check before either inserted, and the room would be double-booked.

Q12. Why is there no "completed" status in the database? Because it would go stale: a stay becomes completed at check-out time, but nothing updates the row at check-out time. Instead completed is computed — status = 'confirmed' and check_out < today — so it is always correct. Seats left is computed the same way.

Q13. How does the system know who is logged in on each page? PHP sessions. After login, the user id, name and role are stored in $_SESSION. Every page includes config.php (which starts the session) and header.php (which calls requireLogin()).

Q14. What is the difference between the admin and the customer? The admin manages hotels, rooms, tours and all bookings and sees the dashboard. The customer only searches, books, views their own bookings and writes reviews. The menu and the page guards enforce this.

Q15. Why one bookings table for rooms and tours instead of two? Because the two kinds share guest, dates, price and status. One table means one booking list, one dashboard query, one cancellation page and one "My Bookings" page instead of two of each. The booking_type column tells them apart.

Q16. How do you stop a customer reviewing a hotel they never stayed in? The review form only lists the customer's own confirmed bookings at that hotel that have not been reviewed yet, and the POST handler re-checks all of that against the database. The database also enforces one review per booking with a UNIQUE key.

Q17. What would you add if you had more time? Online payment, email confirmation, a room availability calendar, a customer "change password" page, and a member-management page for the admin. Payment would add a payments table linked to bookings.

Q18. What was the hardest bug you fixed? (The student should answer from their own testing — for example the overlap rule, or the boundary case where a booking starts on the old check-out day. Do not memorise an answer to this one; it must be true.)


8. Deliverables checklist (what to submit)

  • [ ] SRS document (Section 3 of this guide, written as your own document)
  • [ ] Design document (ERD, architecture, UI flow — Section 4)
  • [ ] Source code (all files in this folder, working)
  • [ ] Database file (schema.sql)
  • [ ] Test report (the test cases in Section 6, with Pass/Fail filled in)
  • [ ] Final report (what you built, how, and what you learned)
  • [ ] Presentation slides for the final viva
  • [ ] Demo video or live demo (run the system on your own laptop)

9. Common errors and fixes

Error / symptom Cause Fix
"Database connection failed" MySQL is not running, or schema.sql was not imported Start MySQL in XAMPP; import schema.sql in phpMyAdmin
"Table 'hotel_db.users' doesn't exist" The schema was imported into the wrong database, or not at all Re-import schema.sql (it creates the database itself)
"headers already sent" Something printed output before session_start() or header() Check for blank lines or spaces before <?php in the file; config.php must be included first
Login always fails The sample users were not imported, or the hash was changed Re-import schema.sql; check the user exists in phpMyAdmin
"This hotel already has a room with that number" Room number is unique inside one hotel This is correct behaviour — use a different room number for that hotel
"Sorry, this room is already booked for those dates" A confirmed booking overlaps the chosen dates This is correct behaviour — pick different dates, or cancel the old booking first
"Only X seat(s) left" The tour departure is nearly full This is correct behaviour — book fewer seats or another date
Apache will not start Port 80 is already in use Stop the other program, or change Apache's port in the XAMPP control panel
Page shows nothing (white screen) A PHP error is hidden by the server settings Temporarily add error_reporting(E_ALL); ini_set('display_errors', '1'); at the top of config.php to see the message, then remove it

10. Future improvements

  1. Online payment — a payments table (booking, amount, method, status) and a payment step after booking; a booking stays "pending" until paid.
  2. Email confirmation — send the booking details to the customer by email after a booking is confirmed or cancelled.
  3. Room availability calendar — a month view per room showing booked and free days, built from the same overlap query.
  4. Change password page — let customers change their own password after first login instead of the admin setting it.
  5. Member management page — let the admin add, edit and suspend customer accounts from the panel instead of the database.
  6. Pagination — split the hotel, room and booking lists into pages when they grow past a few dozen rows.
  7. Laravel version — move the same design to Laravel (Section 4.5): Eloquent models for the six tables, a booking controller with the overlap query inside DB::transaction(), and Blade views for the forms.

Frequently Asked Questions

  1. Which stack does this Hotel and Tour Reservation System use? PHP and MySQL on XAMPP, built in plain PHP + MySQL. The official specification states PHP (Laravel Framework), MySQL, ASP.NET, C# and SQL Server — the same design maps directly to Laravel, and the guide explains how. The demo accounts are admin/admin123 and customer/customer123.
  2. Does the code really work? Yes. It was runtime-verified: all 26 PHP files pass php -l, the schema imports cleanly into MariaDB, the admin and customer logins work, a room booking is refused for overlapping dates and accepted for non-overlapping dates, and cancelling a booking frees the room for those dates again.
  3. Can I use this project for my CS619 final year project? Yes — it follows VU's own phases (SRS, design, coding, testing, viva). Change the sample data, add your own features from the future-improvements list, and write the SRS in your own words before submitting.

Comments

Advertisement
Advertisement

Tool