0% found this document useful (0 votes)
13 views11 pages

import mysql

The document outlines the implementation of an IRCTC system using Python, which includes functionalities for user signup, signin, ticket booking, and ticket checking. It connects to a MySQL database to manage user accounts and bookings, validating inputs such as phone numbers and passwords. The system features a main menu for user interaction and handles exceptions related to database operations.

Uploaded by

babitachand2804
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

import mysql

The document outlines the implementation of an IRCTC system using Python, which includes functionalities for user signup, signin, ticket booking, and ticket checking. It connects to a MySQL database to manage user accounts and bookings, validating inputs such as phone numbers and passwords. The system features a main menu for user interaction and handles exceptions related to database operations.

Uploaded by

babitachand2804
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

import mysql.

connector

import pyfiglet

from datetime import datetime

import re

from typing import Optional, Tuple

class IRCTCSystem:

def __init__(self):

try:

self.conn = mysql.connector.connect(

host='localhost',

user='root',

password='utkarsh',

database='irctc'

self.cursor = self.conn.cursor(buffered=True)

self.conn.autocommit = True

except mysql.connector.Error as err:

print(f"Error connecting to database: {err}")

exit(1)

def display_header(self):

print('+---------------------------------------------------------------------------------------------------------------------------------
---+')

print('\
t+---------------------------------------------------------------------------------------------------------------------------------+')

print(pyfiglet.figlet_format("I R C T C"))

print(pyfiglet.figlet_format('PORTAL'))

print(pyfiglet.figlet_format('20252-26'))
print('\
t+---------------------------------------------------------------------------------------------------------------------------------+')

print('+---------------------------------------------------------------------------------------------------------------------------------
---+')

def validate_phone(self, phone: str) -> bool:

return bool(re.match(r'^[0-9]{10}$', phone))

def validate_password(self, password: str) -> bool:

return len(password) >= 8

def signin(self) -> bool:

username = input('USER NAME: ').strip()

password = input('PASSWORD: ').strip()

try:

query = "SELECT user_name FROM user_accounts WHERE user_name = %s AND password = %s"

self.cursor.execute(query, (username, password))

data = self.cursor.fetchone()

if data and data[0] == username:

print("+---------------------------------------------------------+")

print('\t+------------------------------------------------------+')

print('\t\t+\t\t\t\t\t\tLOGIN SUCCESSFUL +')

print('\t+------------------------------------------------------+')

print('+---------------------------------------------------------+')

return True

else:

print('Invalid credentials. Please try again or create a new account.')


return False

except mysql.connector.Error as err:

print(f"Database error: {err}")

return False

def signup(self) -> bool:

try:

fname = input('FIRST NAME: ').strip()

lname = input('LAST NAME: ').strip()

username = input('USER NAME: ').strip()

password = input('PASSWORD: ').strip()

confirm_password = input('RE ENTER YOUR PASSWORD: ').strip()

phone = input('PHONE NUMBER: ').strip()

if not self.validate_phone(phone):

print("Invalid phone number. Please enter a 10-digit number.")

return False

if not self.validate_password(password):

print("Password must be at least 8 characters long.")

return False

if password != confirm_password:

print('Passwords do not match. Please try again.')

return False

print('M=MALE', '\n', 'F=FEMALE', '\n', 'N=NOT TO MENTION')

gender = input('GENDER: ').upper()

if gender not in ['M', 'F', 'N']:


print("Invalid gender selection.")

return False

print('ENTER YOUR DATE OF BIRTH:')

day = input('DD: ').strip()

month = input('MM: ').strip()

year = input('YYYY: ').strip()

try:

dob = datetime(int(year), int(month), int(day))

age = int(input('ENTER YOUR AGE: ').strip())

except ValueError:

print("Invalid date or age format.")

return False

gender_map = {'M': 'MALE', 'F': 'FEMALE', 'N': 'NOT TO MENTION'}

query = """

INSERT INTO user_account

(fname, lname, user_name, password, phno, gender, dob, age)

VALUES (%s, %s, %s, %s, %s, %s, %s, %s)

"""

values = (fname, lname, username, password, phone, gender_map[gender],

dob.strftime('%Y-%m-%d'), age)

self.cursor.execute(query, values)

print('+------------------------------------------------------------------------------------------+')

print('\t\t\t\t\t\t\t\t\t\t\t\t\t\tYOUR SIGNUP IS SUCCESSFUL')

print('+------------------------------------------------------------------------------------------+')
return True

except mysql.connector.Error as err:

print(f"Database error: {err}")

return False

except Exception as e:

print(f"An error occurred: {e}")

return False

def ticket_booking(self) -> bool:

try:

name = input('Enter your name: ').strip()

phone = input('Enter your phone number: ').strip()

if not self.validate_phone(phone):

print("Invalid phone number. Please enter a 10-digit number.")

return False

age = int(input('Enter your age: ').strip())

print('M=MALE', '\t', 'F=FEMALE', '\t', 'N=NOT TO MENTION')

gender = input('Enter your gender: ').upper()

if gender not in ['M', 'F', 'N']:

print("Invalid gender selection.")

return False

from_station = input('Enter your starting station: ').strip()

to_station = input('Enter your destination: ').strip()


print('Enter journey date:')

day = input('DD: ').strip()

month = input('MM: ').strip()

year = input('YYYY: ').strip()

try:

journey_date = datetime(int(year), int(month), int(day))

except ValueError:

print("Invalid date format.")

return False

gender_map = {'M': 'MALE', 'F': 'FEMALE', 'N': 'NOT TO MENTION'}

query = """

INSERT INTO railways

(name, phno, age, gender, from_f, to_t, date_d)

VALUES (%s, %s, %s, %s, %s, %s, %s)

"""

values = (name, phone, age, gender_map[gender], from_station,

to_station, journey_date.strftime('%Y-%m-%d'))

self.cursor.execute(query, values)

print('+------------------------------------------------------------------------------------------+')

print('\t\t\t\t\t\t\t\t\t\t\t\t\t\tTICKET BOOKED SUCCESSFULLY')

print('+------------------------------------------------------------------------------------------+')

return True

except mysql.connector.Error as err:

print(f"Database error: {err}")


return False

except Exception as e:

print(f"An error occurred: {e}")

return False

def ticket_checking(self) -> bool:

try:

phone = input('ENTER YOUR PHONE NUMBER: ').strip()

if not self.validate_phone(phone):

print("Invalid phone number. Please enter a 10-digit number.")

return False

query = "SELECT * FROM railway WHERE phno = %s"

self.cursor.execute(query, (phone,))

data = self.cursor.fetchone()

if data:

headers = ['NAME', 'PHONE NUMBER', 'AGE', 'GENDER',

'STARTING STATION', 'DESTINATION', 'DATE']

for header, value in zip(headers, data):

print(f"{header}: {value}")

return True

else:

print("TICKET DOES NOT EXIST!!")

return False

except mysql.connector.Error as err:

print(f"Database error: {err}")


return False

def main_menu(self):

while True:

print('''

+----------------------------------------------------------------+

| 1. TICKET BOOKING |

| 2. TICKET CHECKING |

| 3. TICKET CANCELLING |

| 4. ACCOUNT DETAILS |

| 5. VIEW BOOKINGS |

| 6. LOGOUT |

+-----------------------------------------------------------------+

''')

try:

choice = int(input('ENTER YOUR CHOICE: '))

if choice == 1:

self.ticket_booking()

elif choice == 2:

self.ticket_checking()

elif choice == 3:

print("Ticket cancellation feature coming soon!")

elif choice == 4:

print("Account details feature coming soon!")

elif choice == 5:

self.view_bookings()

elif choice == 6:
print('THANK YOU FOR USING IRCTC!')

break

else:

print('Invalid choice. Please try again.')

except ValueError:

print('Please enter a valid number.')

def view_bookings(self):

try:

query = "SELECT * FROM bookings"

self.cursor.execute(query)

bookings = self.cursor.fetchall()

if not bookings:

print("No bookings found.")

return

for booking in bookings:

print("\nBooking Details:")

print("+----------------------------------------------------------------+")

print(f"Booking ID: {booking[0]}")

print(f"Passenger ID: {booking[1]}")

print(f"Train ID: {booking[2]}")

print(f"Journey Date: {booking[3]}")

print(f"Seat Number: {booking[4]}")

print(f"Booking Status: {booking[5]}")

print("+----------------------------------------------------------------+")

except mysql.connector.Error as err:


print(f"Database error: {err}")

def main():

irctc = IRCTCSystem()

irctc.display_header()

while True:

print('''

+====================================================================================
=======================+

| WELCOME TO IRCTC WEBSITE |

| 1. Sign up your IRCTC account |

| 2. Sign in to your IRCTC account |

| 3. See details |

| 4. Logout your account |

| 5. EXIT! |

+====================================================================================
=======================+

''')

try:

choice = int(input('ENTER YOUR CHOICE: '))

if choice == 1:

if irctc.signup():

irctc.main_menu()

elif choice == 2:

if irctc.signin():

irctc.main_menu()
elif choice == 3:

print("Details feature coming soon!")

elif choice == 4:

print("You have been logged out successfully!")

elif choice == 5:

print('''

+-------------------------------------------+

THANK YOU

+-------------------------------------------+

''')

break

else:

print('Invalid choice. Please try again.')

except ValueError:

print('Please enter a valid number.')

if __name__ == "__main__":

main()

You might also like