Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/2feb966505fc6e0032224136e43e88b7 to your computer and use it in GitHub Desktop.
Save code-boxx/2feb966505fc6e0032224136e43e88b7 to your computer and use it in GitHub Desktop.
PHP MYSQL Bus Ticket Booking

PHP MYSQL BUS TICKET BOOKING SYSTEM

https://code-boxx.com/bus-ticket-booking-php/

NOTES

  1. Create a database and import 1-database.sql.
  2. Change the database settings in 2-bus-lib.php to your own.
  3. Access 3a-reservation.php in the browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) AVAILABLE SEATS
CREATE 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');
-- (B) TRIPS
CREATE 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');
-- (C) RESERVATIONS
CREATE 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`);
-- (D) RESERVED SEATS
CREATE 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`);
<?php
class 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) : void {
$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();
<!DOCTYPE html>
<html>
<head>
<title>Bus Ticket Reservation</title>
<meta charset="utf-8">
<script src="3b-reservation.js"></script>
<link rel="stylesheet" href="3c-reservation.css">
</head>
<body>
<?php
// (A) FIXED FOR THIS DEMO
$tripid = 1;
$userid = 999;
// (B) GET TRIP
require "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>
</body>
</html>
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;
}
}
};
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
min-width: 400px;
max-width: 600px;
padding: 10px;
margin: 0 auto;
}
.info, .legend { display: flex; }
/* (B) INFO */
.iLeft, .iRight {
padding: 10px;
border: 1px solid #fff;
}
.iLeft {
width: 100px;
color: #fff;
background: #b72f2f;
}
.iRight {
flex-grow: 1;
background: #f3f3f3;
}
/* (C) SEATS */
/* (C1) WRAPPER */
#layout {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
margin: 20px 0;
}
/* (C2) SEAT "SQUARES" */
#layout .seat {
text-align: center;
padding: 20px;
background: #d4ffd1;
cursor: pointer;
}
.taken { background: #e5e5e5 !important; }
.selected { background: #cbdbff !important; }
/* (C3) LEGEND */
.legend { align-items: center; }
.box {
width: 50px;
padding: 20px;
margin-right: 10px;
background: #d4ffd1;
}
/* (C4) "CHECKOUT FORM" */
#form {
border: 1px solid #ccc;
background: #f3f3f3;
padding: 15px;
margin-top: 15px;
}
#form label, #form input {
display: block;
width: 100%;
}
#form label { padding: 10px 0; }
#form input {
border: 0;
padding: 10px;
}
#form input[type=submit] {
margin-top: 20px;
color: #fff;
background: #b72f2f;
cursor: pointer;
}
<?php
// (A) LOAD LIBRARY
require "2-bus-lib.php";
// (B) SAVE
echo $_BUS->reserve(
$_POST["tid"], $_POST["uid"], $_POST["email"], $_POST["name"], $_POST["seats"]
) ? "OK" : "ERROR" ;
// print_r($_POST);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment