0% found this document useful (0 votes)
10 views15 pages

Yash

The document outlines a Python script for managing an airline reservation system using MySQL. It includes functionalities for creating and updating flight and user tables, adding flights, reserving seats, viewing past reservations, and managing user accounts. The script also provides methods for employees to update user information and manage reservations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views15 pages

Yash

The document outlines a Python script for managing an airline reservation system using MySQL. It includes functionalities for creating and updating flight and user tables, adding flights, reserving seats, viewing past reservations, and managing user accounts. The script also provides methods for employees to update user information and manage reservations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

import mysql.

connector
import datetime

# Connect to the MySQL database


airline_db = mysql.connector.connect(
host="localhost",
user="Manindra",
password="admin123",
database="airline_reservation"
)

cursor = airline_db.cursor()

# Create the 'flights' table if it doesn't exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS flights (
flight_id INT AUTO_INCREMENT PRIMARY KEY,
flight_name VARCHAR(255) NOT NULL,
departure_city VARCHAR(255) NOT NULL,
destination_city VARCHAR(255) NOT NULL,
departure_date DATE NOT NULL,
available_seats INT NOT NULL,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
airline_db.commit()
print("Database Connected.")

# Create the 'users' table if it doesn't exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
airline_db.commit()

# Check if the 'idx_username' index exists before creating it


cursor.execute("SHOW INDEX FROM users WHERE Key_name = 'idx_username'")
if not cursor.fetchone():
cursor.execute("CREATE INDEX idx_username ON users(username)")
airline_db.commit()

# Create the 'employee' table if it doesn't exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS employee (
emp_id INT AUTO_INCREMENT PRIMARY KEY,
emp_cname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
airline_db.commit()

# Create the 'reservations' table if it doesn't exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS reservations (
reservation_id INT AUTO_INCREMENT PRIMARY KEY,
flight_id INT NOT NULL,
username VARCHAR(255) NOT NULL,
seat_number INT NOT NULL,
FOREIGN KEY (flight_id) REFERENCES flights(flight_id),
FOREIGN KEY (username) REFERENCES users(username)
)
""")
airline_db.commit()

# Create the 'past_reservations' table if it doesn't exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS past_reservations (
reservation_id INT AUTO_INCREMENT PRIMARY KEY,
flight_id INT NOT NULL,
username VARCHAR(255) NOT NULL,
seat_number INT NOT NULL,
reservation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (flight_id) REFERENCES flights(flight_id),
FOREIGN KEY (username) REFERENCES users(username)
)
""")
airline_db.commit()

# Function to update a flight's credentials


def update_flight_credentials():
"""
Updates flight information such as flight name, departure city, destination
city, departure date, and available seats.

This function allows an employee to update information related to a flight. It


prompts for the flight ID, checks if the flight exists, and then allows the
employee to update specific details about the flight. The updates are then
committed to the 'flights' table.

Args:
None (user input requested within the function).
Returns:
None.

Examples:
Enter the Flight ID you want to update: 1
Enter the new flight name: Updated Flight
"""
# Prompt the user for the flight ID they want to update
flight_id = input("Enter the Flight ID you want to update: ")

# Check if the flight with the given ID exists


cursor.execute("SELECT * FROM flights WHERE flight_id = %s", (flight_id,))
existing_flight = cursor.fetchone()
print(existing_flight)

if not existing_flight:
print("Flight with the provided ID does not exist.")
choice = int(input("Enter 1 if you want to enter new or otherwise: "))
if choice == 1:
add_flight()
else:
pass
return

# Prompt the user for the new values


flight_name = input("Enter the new flight name (or press Enter to keep it
unchanged): ")
departure_city = input("Enter the new departure city (or press Enter to keep it
unchanged): ")
destination_city = input("Enter the new destination city (or press Enter to
keep it unchanged): ")
departure_date = input("Enter the new departure date (YYYY-MM-DD) (or press
Enter to keep it unchanged): ")
available_seats = input("Enter the new number of available seats (or press
Enter to keep it unchanged): ")

# Construct the UPDATE query based on the provided input


update_query = "UPDATE flights SET "
update_values = []

if flight_name:
update_query += "flight_name = %s, "
update_values.append(flight_name)
if departure_city:
update_query += "departure_city = %s, "
update_values.append(departure_city)
if destination_city:
update_query += "destination_city = %s, "
update_values.append(destination_city)
if departure_date:
update_query += "departure_date = %s, "
update_values.append(departure_date)
if available_seats:
update_query += "available_seats = %s, "
update_values.append(available_seats)

# Remove the trailing comma and space from the query


update_query = update_query.rstrip(", ")

# Add the WHERE clause to specify which flight to update


update_query += " WHERE flight_id = %s"
update_values.append(flight_id)

try:
# Execute the UPDATE query with the new values
cursor.execute(update_query, update_values)
airline_db.commit()
print("Flight credentials updated successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")

# Function to add a new flight


def add_flight():
"""
Adds a new flight to the database.

This function allows an employee to add a new flight to the 'flights' table. It
prompts for flight details such as flight name, departure city, destination city,
departure date, and available seats.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the flight name: New Flight
Enter the departure city: Departure City
"""
flight_name = input("Enter the flight name: ")
departure_city = input("Enter the departure city: ")
destination_city = input("Enter the destination city: ")
departure_date = input("Enter departure date (YYYY-MM-DD): ")
available_seats = int(input("Enter the number of available seats: "))

# Insert the new flight into the 'flights' table


insert_query = """
INSERT INTO flights (flight_name, departure_city, destination_city,
departure_date, available_seats)
VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(insert_query, (flight_name, departure_city, destination_city,
departure_date, available_seats))
airline_db.commit()
print("Flight added successfully!")

# Function to list available flights


def list_flights():
"""
Lists available flights in the database.

This function retrieves and displays a list of available flights from the
'flights' table. It provides information about each flight, including its ID, name,
departure city, destination city, departure date, and available seats.

Args:
None.

Returns:
None. (Prints the list of flights to the console)

Examples:
list_flights()
"""
cursor.execute("SELECT * FROM flights")
flights = cursor.fetchall()
if not flights:
print("No flights available.")
else:
print("Available Flights:")
for flight in flights:
print(f"Flight ID: {flight[0]}, Flight Name: {flight[1]}, Departure
City: {flight[2]}, Destination City: {flight[3]}, Departure Date: {flight[4]},
Available Seats: {flight[5]}")

# Function to register a new user


def register_user(username, email, password):

# Check if the username is already registered


cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
existing_user = cursor.fetchone()
if existing_user:
print("User with this username already exists.")
return

# Insert the new user into the 'users' table


insert_query = """
INSERT INTO users (username, email, password)
VALUES (%s, %s, %s)
"""
cursor.execute(insert_query, (username, email, password))
airline_db.commit()
print("User registered successfully!")

# Function to check if a flight exists and has available seats


def flight_exists_and_has_available_seats(flight_id):
# Check if the flight exists
cursor.execute("SELECT * FROM flights WHERE flight_id = %s", (flight_id,))
flight = cursor.fetchone()

if not flight:
# Flight does not exist
return False

# Check if there are available seats


available_seats = flight[5] # Assuming available seats column is at index 5
cursor.execute("SELECT COUNT(*) FROM reservations WHERE flight_id = %s",
(flight_id,))
reservations_count = cursor.fetchone()[0]

if available_seats > reservations_count:


# There are available seats
return True
else:
# No available seats
return False

# Function to reserve a seat on a flight


def reserve_seat():
"""
Reserves a seat on a flight if available.

This function allows a user to reserve a seat on a flight if available seats


exist. It checks the availability of seats on the flight, validates user inputs,
inserts the reservation into the 'reservations' table, and updates the
'past_reservations' table with reservation details.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the flight ID you want to reserve a seat on: 1
Enter your username: Ankit
Enter the seat number you want to reserve: 5
"""
flight_id = input("Enter the flight ID you want to reserve a seat on: ")

# Check if the flight exists and has available seats


if flight_exists_and_has_available_seats(flight_id):
username = input("Enter your username: ")
seat_number = int(input("Enter the seat number you want to reserve: "))

# Insert the reservation into the 'reservations' table


insert_query = """
INSERT INTO reservations (flight_id, username, seat_number)
VALUES (%s, %s, %s)
"""
cursor.execute(insert_query, (flight_id, username, seat_number))
airline_db.commit()

# Get the reservation_id of the newly inserted reservation


reservation_id = cursor.lastrowid # This gets the auto-incremented ID

# Insert the reservation into the 'past_reservations' table with


reservation_id
insert_query = """
INSERT INTO past_reservations (reservation_id, flight_id, username,
seat_number)
VALUES (%s, %s, %s, %s)
"""
cursor.execute(insert_query, (reservation_id, flight_id, username,
seat_number))
airline_db.commit()

print("Seat reserved successfully.")


else:
print("This flight is not available or has no more seats.")

# Function to display user's past reservations


def view_past_reservations(username):
"""
Retrieves and displays a user's past flight reservations.

This function fetches past flight reservations for a specific user and displays
them. It retrieves data from the 'past_reservations' and 'flights' tables, joining
them to provide a comprehensive list of past reservations.

Args:
username (str): The username for which past reservations are to be
retrieved.

Returns:
None. (Prints the past reservations to the console)

Examples:
view_past_reservations("Ankit")
"""

cursor.execute("""
SELECT pr.reservation_id, f.flight_name, f.departure_city,
f.destination_city, pr.seat_number, pr.reservation_date
FROM past_reservations pr
JOIN flights f ON pr.flight_id = f.flight_id
WHERE pr.username = %s
""", (username,))
past_reservations = cursor.fetchall()

if not past_reservations:
print("You have no past reservations.")
else:
print("Your Past Reservations:")
for reservation in past_reservations:
print(f"Reservation ID: {reservation[0]}, Flight Name:
{reservation[1]}, Departure City: {reservation[2]}, Destination City:
{reservation[3]}, Seat Number: {reservation[4]}, Reservation Date:
{reservation[5]}")

# Function to check if a user exists and has the correct password


def if_User(username, email, password):
# Check if the provided username exists in the 'users' table
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
user_row = cursor.fetchone()

if user_row:
# Username exists in 'users' table
if user_row[3] == password: # Assuming the password column is at index 3
return True
else:
return "WRONG PASSWORD!"
else:
# User does not exist, so register the user
print("Oops! Looks like you are not registered in our database. :(")
choice = input("Enter 1 if you want to register or 2 to otherwise: ")
if choice == "1":
register_user(username, email, password)
else:
return True # Return True after registration

# Function to check if an employee exists and has the correct password


def if_Employee(username, password):
# Check if the provided username exists in the 'employee' table
cursor.execute("SELECT * FROM employee WHERE emp_cname = %s", (username,))
employee_row = cursor.fetchone()
if employee_row:
# Username exists in 'employee' table
if employee_row[3] == password: # Use integer index to access the
"password" column
return "EMPLOYEE"
else:
print("WRONG EMPLOYEE PASSWORD!")
else:
print("EMPLOYEE DOES NOT EXIST")

# Function to update user information by employees


def update_user_info():
"""
Updates user information, such as email or password, by an employee.

This function is used by employees to update user information. It prompts for a


username, verifies user existence, and allows the employee to update the user's
email or password. The function also performs the necessary database updates.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the username of the user you want to update: Ankit
"""
username = input("Enter the username of the user you want to update: ")

# Check if the user exists


cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
existing_user = cursor.fetchone()

if not existing_user:
print("User with the provided username does not exist.")
return

print("Select the information you want to update:")


print("1. Email")
print("2. Password")

choice = input("Enter your choice: ")

if choice == "1":
new_email = input("Enter the new email address: ")
cursor.execute("UPDATE users SET email = %s WHERE username = %s",
(new_email, username))
airline_db.commit()
print("User's email updated successfully.")
elif choice == "2":
new_password = input("Enter the new password: ")
cursor.execute("UPDATE users SET password = %s WHERE username = %s",
(new_password, username))
airline_db.commit()
print("User's password updated successfully.")
else:
print("Invalid choice.")

# Function to cancel or update user reservations by employees


def cancel_or_update_reservation():
"""
Cancels or updates user flight reservations.

This function allows an employee to perform actions related to a user's flight


reservations. The employee can choose to cancel a reservation by specifying the
Reservation ID or update an existing reservation's seat number.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the username of the user whose reservation you want to cancel or
update: john_doe
"""
username = input("Enter the username of the user whose reservation you want to
cancel or update: ")

# Check if the user exists


cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
existing_user = cursor.fetchone()

if not existing_user:
print("User with the provided username does not exist.")
return

# Display user's reservations


cursor.execute("SELECT * FROM reservations WHERE username = %s", (username,))
reservations = cursor.fetchall()

if not reservations:
print("No reservations found for this user.")
return

print("User's Reservations:")
for reservation in reservations:
print(f"Reservation ID: {reservation[0]}, Flight ID: {reservation[1]}, Seat
Number: {reservation[3]}")
print("Select the action you want to perform:")
print("1. Cancel Reservation")
print("2. Update Reservation")

choice = input("Enter your choice: ")

if choice == "1":
reservation_id = input("Enter the Reservation ID you want to cancel: ")
cursor.execute("DELETE FROM reservations WHERE reservation_id = %s",
(reservation_id,))
airline_db.commit()
print("Reservation canceled successfully.")
elif choice == "2":
reservation_id = input("Enter the Reservation ID you want to update: ")
new_seat_number = input("Enter the new seat number: ")
cursor.execute("UPDATE reservations SET seat_number = %s WHERE
reservation_id = %s", (new_seat_number, reservation_id))
airline_db.commit()
print("Reservation updated successfully.")
else:
print("Invalid choice.")

# Function to edit past reservations by employee


def edit_past_reservations_by_employee():
"""
Allows an employee to edit past flight reservations.

This function enables an employee to edit specific details of past flight


reservations, such as the seat number. It prompts for the Reservation ID, validates
input, and updates the 'past_reservations' table with the new seat number.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the Reservation ID you want to edit: 1
"""
reservation_id = input("Enter the Reservation ID you want to edit: ")

# Check if the reservation exists


cursor.execute("""
SELECT pr.reservation_id, pr.flight_id, pr.username, pr.seat_number,
f.available_seats
FROM past_reservations pr
JOIN flights f ON pr.flight_id = f.flight_id
WHERE pr.reservation_id = %s
""", (reservation_id,))
reservation_info = cursor.fetchone()

if not reservation_info:
print("Reservation with the provided ID does not exist.")
return

print("Select the information you want to update:")


print("1. Seat Number")

choice = input("Enter your choice: ")

if choice == "1":
new_seat_number = input("Enter the new seat number: ")
if 1 <= int(new_seat_number) <= reservation_info[4]:
cursor.execute("UPDATE past_reservations SET seat_number = %s WHERE
reservation_id = %s", (new_seat_number, reservation_id))
airline_db.commit()
print("Reservation updated successfully.")
else:
print("Invalid seat number. Please select a valid seat.")
else:
print("Invalid choice.")

# Function to handle user menu


def user_menu():
username = input("Enter username: ")
password = input("Enter password: ")
email = input("Enter your EMAIL ID: ")
if if_User(username, email, password):
check = 0
while check == 0:
print("\nUser Menu:")
print("1. List Available Flights")
print("2. Reserve a Seat")
print("3. View Past Reservations")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":
list_flights()
elif choice == "2":
reserve_seat()
elif choice == "3":
view_past_reservations(username)
elif choice == "4":
check = 1
else:
print("Invalid choice. Please try again.")

# Function to add a new user by an employee


def add_user_by_employee():
"""
Adds a new user to the database by an employee.

This function allows an employee to add a new user to the 'users' table. It
prompts for the new user's username, email, and password, performs a check to
ensure the username is unique, and adds the new user to the database.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the username of the new user: new_user
"""
username = input("Enter the username of the new user: ")
email = input("Enter the email of the new user: ")
password = input("Enter the password for the new user: ")

# Check if the username is already registered


cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
existing_user = cursor.fetchone()
if existing_user:
print("User with this username already exists.")
return

# Insert the new user into the 'users' table


insert_query = """
INSERT INTO users (username, email, password)
VALUES (%s, %s, %s)
"""
cursor.execute(insert_query, (username, email, password))
airline_db.commit()
print("User added successfully by employee!")

# Function to remove an existing user by an employee


def remove_user_by_employee():
"""
Removes an existing user from the database by an employee.

This function allows an employee to remove an existing user from the 'users'
table. It prompts for the username of the user to be removed, verifies user
existence, and performs the user removal.

Args:
None (user input requested within the function).

Returns:
None.

Examples:
Enter the username of the user you want to remove: john_doe
"""
username = input("Enter the username of the user you want to remove: ")

# Check if the user exists


cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
existing_user = cursor.fetchone()

if not existing_user:
print("User with the provided username does not exist.")
return

# Delete the user from the 'users' table


delete_query = "DELETE FROM users WHERE username = %s"
cursor.execute(delete_query, (username,))
airline_db.commit()
print("User removed successfully by employee!")

# Function to handle employee menu


def employee_menu():
username = input("Enter username: ")
password = input("Enter password: ")

if if_Employee(username, password) == "EMPLOYEE":


check = 0
while check == 0:
print("\nEmployee Menu:")
print("1. List Available Flights")
print("2. Update Flight Credentials")
print("3. Update User Information")
print("4. Cancel or Update User Reservation")
print("5. Edit Past Reservations")
print("6. Add User")
print("7. Remove User")
print("8. Exit")

choice = input("Enter your choice: ")

if choice == "1":
list_flights()
elif choice == "2":
update_flight_credentials()
elif choice == "3":
update_user_info()
elif choice == "4":
cancel_or_update_reservation()
elif choice == "5":
edit_past_reservations_by_employee()
elif choice == "6":
add_user_by_employee()
elif choice == "7":
remove_user_by_employee()
elif choice == "8":
check = 1
else:
print("Invalid choice. Please try again.")

# Function to display the main menu


def main_menu():
while True:
print("\nMain Menu:")
print("1. User Login")
print("2. Employee Login")
print("3. Exit")

choice = input("Enter your choice: ")

if choice == "1":
user_menu()
elif choice == "2":
employee_menu()
elif choice == "3":
break
else:
print("Invalid choice. Please try again.")

# Call the main menu function


main_menu()

# Close the cursor and database connection


cursor.close()
airline_db.close()

You might also like