Welcome to a tutorial on how to create a simple bus ticket booking system in PHP and MySQL. Working for a client who is going to run a fleet of buses? Or just doing this as an old-school assignment? Well, here’s a simple booking system that will kickstart your project. Read on!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
Ticket Reservation System in PHP Fr... Ticket Reservation System in PHP Free Download with QR Code | PHP Projects with Source Code
TABLE OF CONTENTS
PHP Bus Ticket Booking
The End
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
- Create a database and import
1-database.sql
. - Change the database settings in
2-bus-lib.php
to your own. - Access
3a-reservation.php
in the browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
SCREENSHOT
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
PHP MYSQL BUS TICKET BOOKING
All right, let us now get into more details on how the PHP MYSQL bus ticket booking system works.
PART 1) THE DATABASE
1A) SEATS TABLE
1-database.sql
-- (A) AVAILABLE SEATSCREATE TABLE `seats` ( `bus_id` varchar(16) NOT NULL, `seat_id` varchar(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;ALTER TABLE `seats` ADD PRIMARY KEY (`seat_id`,`bus_id`);INSERT INTO `seats` (`bus_id`, `seat_id`) VALUES('BUS-A', 'A1'),('BUS-A', 'A2'),('BUS-A', 'A3'),('BUS-A', 'A4'),('BUS-A', 'B1'),('BUS-A', 'B2'),('BUS-A', 'B3'),('BUS-A', 'B4'),('BUS-A', 'C1'),('BUS-A', 'C2'),('BUS-A', 'C3'),('BUS-A', 'C4');
This table should be self-explanatory, to store the seats available on the buses.
bus_id
Partial primary key, vehicle registration number.seat_id
Partial primary key.
Well, feel free to add more fields as required – Window seat, smoking allowed, or even invent your own “grid system” to properly store the seat layout.
1B) TRIPS TABLE
1-database.sql
-- (B) TRIPSCREATE TABLE `trips` ( `trip_id` bigint(20) NOT NULL, `bus_id` varchar(16) NOT NULL, `trip_date` datetime NOT NULL, `trip_from` varchar(255) NOT NULL, `trip_to` varchar(255) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;ALTER TABLE `trips` ADD PRIMARY KEY (`trip_id`), ADD KEY `bus_id` (`bus_id`), ADD KEY `trip_date` (`trip_date`);ALTER TABLE `trips` MODIFY `trip_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;INSERT INTO `trips` (`trip_id`, `bus_id`, `trip_date`, `trip_from`, `trip_to`) VALUES(1, 'BUS-A', '2077-06-05 00:00:00', 'Point A', 'Point B');
trip_id
Primary key, auto-increment.bus_id
Foreign key.trip_date
When the trip takes place.trip_from
Board the bus here.trip_to
Destination.
1C) RESERVATIONS TABLE
1-database.sql
-- (C) RESERVATIONSCREATE TABLE `reservations` ( `trip_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `email` varchar(255) NOT NULL, `name` varchar(255) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;ALTER TABLE `reservations` ADD PRIMARY KEY (`trip_id`, `user_id`), ADD KEY `email` (`email`);
trip_id
Partial primary and foreign key.user_id
Partial primary and foreign key.email
Customer’s email.name
Customer’s name.
Some of you sharp code ninjas should have question marks over why we are storing the email and name, when we can retrieve the data from the user table. This is not redundant, customers may be booking for someone else or on behalf of their company.
P.S. Add more fields as necessary again.
1D) RESERVED SEATS
1-database.sql
-- (D) RESERVED SEATSCREATE TABLE `reserve_seats` ( `trip_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `seat_id` varchar(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `reserve_seats` ADD PRIMARY KEY (`trip_id`, `user_id`, `seat_id`);
A “sub table” for reservations, to store which seats are selected. trip_id user_id seat_id
are all primary and foreign keys.
PART 2) PHP LIBRARY
2-bus-lib.php
<?phpclass Bus { // (A) CONSTRUCTOR - CONNECT TO DATABASE private $pdo = null; private $stmt = null; public $error = null; function __construct () { $this->pdo = new PDO( "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET, DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); } // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION function __destruct () { if ($this->stmt !== null) { $this->stmt = null; } if ($this->pdo !== null) { $this->pdo = null; } } // (C) HELPER FUNCTION - RUN SQL QUERY function query ($sql, $data=null) { $this->stmt = $this->pdo->prepare($sql); $this->stmt->execute($data); } // (D) ADD/EDIT TRIP function trip ($bus, $date, $from, $to, $tid=null) { // (D1) SQL & DATA if ($tid==null) { $sql = "INSERT INTO `trips` (`bus_id`, `trip_date`, `trip_from`, `trip_to`) VALUES (?,?,?,?)"; $data = [$bus, $date, $from, $to]; } else { $sql = "UPDATE `trips` SET `bus_id`=?, `trip_date`=?, `trip_from`=?, `trip_to`=? WHERE `trip_id`=?"; $data = [$bus, $date, $from, $to, $tid]; } // (D2) RESULTS $this->query($sql, $data); return true; } // (E) GET GIVEN TRIP function get ($tid) { // (E1) TRIP DATA $this->query("SELECT * FROM `trips` WHERE `trip_id`=?", [$tid]); $trip = $this->stmt->fetch(); if (!is_array($trip)) { return false; } // (E2) SEATS $this->query( "SELECT s.`seat_id`, r.`user_id` FROM `seats` s LEFT JOIN `trips` t USING (`bus_id`) LEFT JOIN `reserve_seats` r USING(`seat_id`) WHERE t.`trip_id`=? ORDER BY s.`seat_id`", [$tid] ); $trip["seats"] = $this->stmt->fetchAll(); return $trip; } // (F) SAVE RESERVATION function reserve ($tid, $uid, $email, $name, $seats) { // (F1) RESERVATIONS TABLE $this->query( "INSERT INTO `reservations` (`trip_id`, `user_id`, `email`, `name`) VALUES (?,?,?,?)", [$tid, $uid, $email, $name] ); // (F2) SELECTED SEATS $sql = "INSERT INTO `reserve_seats` (`trip_id`, `user_id`, `seat_id`) VALUES "; foreach ($seats as $seat) { $sql .= "(?,?,?),"; $data[] = $tid; $data[] = $uid; $data[] = $seat; } $sql = substr($sql, 0, -1); $this->query($sql, $data); return true; }}// (G) DATABASE SETTINGS - CHANGE TO YOUR OWN!define("DB_HOST", "localhost");define("DB_NAME", "test");define("DB_CHARSET", "utf8mb4");define("DB_USER", "root");define("DB_PASSWORD", "");// (H) NEW BUS BOOKING OBJECT$_BUS = new Bus();
The library may look massive at first, but keep and look closely.
- (A, B, H) When
$_BUS = new Bus()
is created, the constructor connects to the database. The destructor closes the connection. - (C)
query()
A simple helper function to run an SQL statement. - (D To F) The “actual” booking functions.
trip()
Add or edit a trip.get()
Get the specified trip.reserve()
Save a reservation.
- (G) Self-explanatory. Change the settings to your own.
PART 3) TICKET BOOKING PAGE
3A) THE HTML
3a-reservation.php
<?php// (A) FIXED FOR THIS DEMO$tripid = 1;$userid = 999;// (B) GET TRIPrequire "2-bus-lib.php";$trip = $_BUS->get($tripid);?><!-- (C) TRIP INFO --><div class="info"> <div class="iLeft">Date</div> <div class="iRight"><?=$trip["trip_date"]?></div></div><div class="info"> <div class="iLeft">From</div> <div class="iRight"><?=$trip["trip_from"]?></div></div><div class="info"> <div class="iLeft">To</div> <div class="iRight"><?=$trip["trip_to"]?></div></div> <!-- (D) DRAW SEATS LAYOUT --><div id="layout"><?php foreach ($trip["seats"] as $s) { $taken = is_numeric($s["user_id"]); printf("<div class='seat%s'%s>%s</div>", $taken ? " taken" : "", $taken ? "" : " onclick='reserve.toggle(this)'", $s["seat_id"] );} ?></div> <!-- (E) LEGEND --><div class="legend"> <div class="box"></div> Open</div><div class="legend"> <div class="box taken"></div> Taken</div><div class="legend"> <div class="box selected"></div> Your selected seats</div> <!-- (F) SAVE RESERVATION --><form id="form" method="post" action="4-save.php" onsubmit="return reserve.save();"> <input type="hidden" name="tid" value="<?=$tripid?>"> <input type="hidden" name="uid" value="<?=$userid?>"> <label>Name</label> <input type="text" name="name" required value="Jon Doe"> <label>Email</label> <input type="email" name="email" required value="jon@doe.com"> <input type="submit" value="Reserve Seats"></form>
Not going to explain the HTML page line-by-line, but a quick walkthrough:
- (A & B) Load the PHP library, and get information on the trip. The trip id and user id are fixed for this demo.
- (C) Information on the trip itself.
- (D) Seats layout and select a seat.
- (E) Seats legend.
- (F) “Checkout form”.
3B) THE JAVASCRIPT
3b-reservation.js
var reserve = { // (A) CHOOSE THIS SEAT toggle : seat => seat.classList.toggle("selected"), // (B) SAVE RESERVATION save : () => { // (B1) GET SELECTED SEATS var selected = document.querySelectorAll("#layout .selected"); // (B2) ERROR! if (selected.length == 0) { alert("No seats selected."); return false; } // (B3) NINJA FORM SUBMISSION else { var form = document.getElementById("form"); for (let seat of selected) { let input = document.createElement("input"); input.type = "hidden"; input.name = "seats[]"; input.value = seat.innerHTML; form.appendChild(input); } return true; } }};
This one just simply inserts the selected seats into the HTML form before submission.
PART 4) “CHECKOUT”
4-save.php
<?php// (A) LOAD LIBRARYrequire "2-bus-lib.php";// (B) SAVEecho $_BUS->reserve( $_POST["tid"], $_POST["uid"], $_POST["email"], $_POST["name"], $_POST["seats"]) ? "OK" : "ERROR" ;// print_r($_POST);
Right, this dummy “checkout page” simply saves the booking request. Complete your own –
- Require the customer to pay first?
- Send a confirmation email?
- User registration required?
- Show a nice “thank you” page.
You decide.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
COMPLETE YOUR OWN SYSTEM!
I can hear the trolls singing “this is not a complete system”! Well, this is a simple tutorial, there are plenty of things to consider:
- If you don’t already have an existing user system, see the links below.
- If you don’t already have an existing admin panel, see the links below.
- Decide if you require users to be registered before allowing them to book, open for public booking (no registration required), or auto register when they “checkout”.
- Decide if you want to restrict the number of seats a customer can book, or if they need to manually call to book the entire bus.
- Complete your own online payment if you require customers to pay before booking.
- Complete your own processes – Send email confirmation? Send SMS? Verifications required for cross-border services? Documents?
- Do your own reports.
- Beef up on your own security and checks.
It is impossible to create a “one size fits all system”, and I cannot provide free consultation for everyone – “Complete the system” is your own homework.
LINKS & REFERENCES
- Simple User Login With PHP MySQL – Code Boxx
- User Registration With Email Verification – Code Boxx
- Simple PHP MySQL Admin Panel – Code Boxx
- Simple User Role Management – Code Boxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
FAQs
Which is a valid website for booking bus tickets? ›
Goibibo is a one-stop destination for online booking bus. Bus booking can be done from anywhere and Goibibo ensures that your bus journey is a smooth one.
What is bus booking API? ›API is a shrewd and instinctive online travel ticket booking portal, offering on the web bus ticket booking services in India. Straightforward commissions at search time itself guaranteeing customer to deal with their review in a better manner.
What is bus ticket system? ›A bus reservation system is a mobile or web software solution designed to provide customers with a personalized easy-to-utilize user experience for booking and purchasing tickets online. It stores customers' personal data records, scheduled routes, frequent trips, drop points, and other information.
How do you create a simple ticketing system? ›- Step 1 - Create the open support form. Sign into Google Docs with your Gmail login. ...
- Step 2 - Enter Data. You can now manually enter your data into the form. ...
- Step 3 - Assign tasks. ...
- Step 4 - Train team members. ...
- Step 5 - Manually close the ticket.
- Enter company details.
- Add products and inventory.
- Customize the Booking Page.
- Enable an online payment flow.
- Connect booking system to website.
- Automate booking notifications.
- Create digital waivers and documents.
- Assign users and commissions.
eTravelSmart
With what is regarded as India's largest bus inventory, eTravelSmart gives its customers the option to reserve seats for just 20% of the entire ticket price. While making a reservation through the phone, mobile app, or online, the business provides excellent deals and discounts.
EaseMyTrip is a wonderful platform for all bus travelers. Discover your favorite place through luxury bus or budgeted bus including sleeper, AC/NON-Ac, Volvo, semi-sleeper, and room.
What is the name of the website for online ticket booking? ›- MakeMyTrip. Makemytrip is one of the best website for flight booking in India, and anyone can easily join in and make an account. ...
- Goibibo. Goibibo, a unit of the Ibibo Group, also owns RedBus.in, India's top online bus ticketing website. ...
- Cleartrip. ...
- Yatra. ...
- EaseMyTrip. ...
- Skyscanner. ...
- Thomas Cook. ...
- Expedia.
If booking.com approves your partnership application, you'll have to present your project of integration with the booking.com platform, be it on a website or application. Only after this multi-stage approval your partner account will be activated and you will get Booking.com integration API.
How do bus apps work? ›The bus tracking system uses GPS technology and software applications to track the location of buses and provide real-time updates to operators and passengers. These systems allow passengers to track buses in real-time, making sure they know exactly when the next bus will arrive.
What are 4 functions of the bus ticket reservation system? ›
With the bus ticket reservation system, you can manage reservations, client data, passenger lists, and fares. Even if you are able to manage scheduled routes, set seat availability, upload an interactive seat map.
Which model is used for bus reservation system? ›OBTRS is designed to manage and compile a traditional database, ticket booking and bus tracking and departure made. Maintains all customer details, bus details, booking details.
How does ticket booking work? ›An online booking system uses smart technology that eliminates the risks associated with manual input and human error. It simplifies the booking process for you and your customers by automatically updating processes such as payment, scheduling, managing availability and notification reminders.
Can you use Google Forms as a ticketing system? ›IT support and help teams use ticketing systems to manage, store and organize support requests. While there are many good ticketing systems out there, you can hack together your own with a tool using Google Forms.
What is single ticketing system? ›The single ticketing system seeks to “harmonize the existing national and local laws on traffic enforcement to establish an effective transport and traffic management system in Metro Manila.” MMDA acting chairman Don Artes also said this would minimize corruption between the driver and the enforcer.
How to create a booking form in HTML? ›- After editing your Booking Forms template, sign in to your Elfsight account.
- Get the unique form code.
- Enter the form code into your HTML editor.
- Congrats! You have added the Booking Forms widget to the HTML webpage successfully.
On average starting price for a good online scheduling system is $30 per month and for that money, you will receive valuable insights for your marketing, among a number of other major benefits.
What is party bus app? ›Partybus is a dedicated hangout spot for you to connect with other GenZ'ers over mutual interests, whether it be music, memes, or mental health. It is also ideal if you want to delve deeper into pressing issues, build community, and discuss how we can support each other to work towards a more equitable world.
Is bus carousel free? ›The Service Contracting program, which allows for free rides on EDSA Carousel buses and on other public utility vehicles, has received a budget of P1. 28 billion under the 2023 General Appropriations Act, said Budget Sec.
Can you buy a bus ticket at the counter? ›You can buy bus tickets to TBS and from TBS at the physical ticket counter located at the bus terminal. It is easy to book tickets to TBS and from TBS online. You can get online tickets in less than 5 mins. No, it is not compulsory to register to book TBS online tickets.
What is the meaning of 2 1 in bus? ›
Some buses allow you to book a double sleeper seat or a single sleeper seat. As an example, you will see this when booking bus tickets as “2+1,” with the “2” being a double, and the “1” being a single. If you're traveling with a partner, then you'll probably prefer to book the double.
How do I download tickets from a website? ›- Steps by Step Instruction to Print Indian Rail Train Ticket from IRCTC Website.
- 1) Open IRCTC Website.
- 2) Log on IRCTC Website.
- 3) Open Booked Ticket History Page.
- 4) Print IRCTC Train Ticket ( E-Ticket)
An online booking system is a software solution and reservation system that makes it simple for guests to book and pay for your tours and activities online. Some of these systems also include reporting software for tour operators and other user-friendly tools that help you improve efficiencies and boost bookings.
How to get an API for free? ›- HubSpot API.
- Yahoo Search Marketing API.
- Common Crawl.
- Google APIs.
- WordPress APIs.
- Sejda PDF API.
- QRcode Monkey.
- Telegram API.
There are no minimum fees or upfront commitments. For HTTP APIs and REST APIs, you pay only for the API calls you receive and the amount of data transferred out. There are no data transfer out charges for Private APIs. However, AWS PrivateLink charges apply when using Private APIs in API Gateway.
How to deploy API for free? ›The first way to host your API is directly from your local computer. Even though this sounds weird, it's pretty easy and for free. While you are developing your API using express or any other library you host it in your localhost:3000 where 3000 is the port through which the network request happens.
What app to use for bus? ›Singabus - Bus Timing + MRT 4+
How do bus QR codes work? ›Here are a few steps for how to use them:
On iOS - iPhone, iPad and iPod Touch that runs on iOS11 or for Android users - Google on Tap, Google Assistant or Google Lens. Open your camera app and point it steady towards the QR codes you want to scan at the stop. Your live bus times will automatically appear.
A: Whilst you don't need an internet connection at the point you activate an already purchased ticket, a regular internet connection is required by the app to keep content upto date and secure.
What programming language does Amadeus use? ›As you are aware, Amadeus Self-Service APIs are supported by open-source SDKs (Software Development Kits) in GitHub with 8 programming languages (Java, Python, Node, PHP, Android, Ruby, iOS, . NET).
Is Amadeus for developers free? ›
In the test environment, you get a free request quota each month to build and fine-tune your apps. When you move to production, you maintain your free request quota and pay only for the additional calls you make.
How to access data using API? ›- Configure the API endpoint. An API endpoint can be complex. ...
- Create an API resource. ...
- Store data into a database. ...
- Transform the API data. ...
- Export the data to an application. ...
- Check and maintain the pipeline.
The term “bus” is used to represent a group of electrical signals or the wires that carry these signals. As shown in Figure 1.5, the system bus consists of three major components: an address bus, a data bus, and a control bus. memory. Furthermore, each data transfer can move 64 bits of data.
What are the four types of system bus? ›- Address bus - carries memory addresses from the processor to other components such as primary storage and input/output devices. The address bus is unidirectional .
- Data bus - carries the data between the processor and other components. ...
- Control bus - carries control signals from the processor to other components.
- GN. General Quota.
- LD. Ladies Quota.
- HO. Head quarters/high official Quota.
- DF. Defence Quota.
- PH. Parliament house Quota.
- FT. Foreign Tourist Quota.
- DP. Duty Pass Quota.
- tq. Tatkal Quota.
The unique ID in the RFID cards are stored in a database in the internet along with personal data and creates accounts for each person. By accessing this database, it is thus possible to identify the traveller, check his account and deduct the fare from his/her account.
What was the first model of bus? ›The first vehicle was delivered to the “Netphener Omnibus-Gesellschaft mbH” bus company in the Siegerland region of Germany, today part of the state of North Rhine-Westphalia. The world's first motorized bus went into service on 18 March 1895. 5 PS to carry eight people.
What is the objective of online bus ticket reservation system? ›The purpose of an online booking system is to allow potential customers to self-book and pay through your website, securely store customer's data, manage your staff and keep your business running long after you've gone home for the day.
How many tickets can be booked in a day? ›As per Indian Railways rules, a maximum of four passengers per PNR can be booked on Tatkal e-ticket. A person is allowed to book up to 4 tatkal tickets on one PNR.
How many tickets can be booked at a time? ›An individual user can book a maximum of six tickets in a calendar month.
What is the difference between booking and ticketing? ›
Ticketing and booking are two separate processes. Booking just holds the seat on the plane. Ticketing means that the seat is paid for and the passenger has the right to take it during the flight.
What do I need in a ticketing system? ›- Multi-channel accessibility. ...
- Support for multiple languages. ...
- Full customization. ...
- Workflow automation. ...
- Personalized ticket pages. ...
- Ticket categories and tags. ...
- Knowledge base. ...
- Team empowerment.
redBus is the most popular app for booking bus tickets. You may use this app to search through various Indian cities and purchase bus tickets for either sleeper or Volvo buses.
What is an example of a ticketing system? ›Freshdesk
Freshdesk is a cloud-based ticketing support system that has all the necessary IT support features in one place, making it a popular Zendesk alternative. The functionality varies based on your plan but all plans include ticket management, team collaboration, social ticketing, and reporting.
If you're still unfamiliar, the single ticketing system harmonizes all the local laws on traffic enforcement, meaning the violations cited by enforcers will be uniform across various cities in the metro. In addition, motorists will no longer be required to settle their fines in the city where they were apprehended.
What is the bus system in C language? ›Introduction. The Bus Reservation System is a basic console program that runs on the C platform and has no visuals. The system uses bus information, which includes the bus number, seat number, and the passenger's name, to book a seat on the bus. Under the passenger's name, the specific bus seat number is booked.