import mysql.connector
from datetime import datetime, timedelta
# Function to connect to the database
def connect_db():
return mysql.connector.connect(
host="localhost",
user="root", # Replace with your MySQL username
password="Abhishekrajbhar@06", # Replace with your MySQL password
database="attendance_db"
)
# Function to register a new user
def register_user():
username = input("Enter username: ")
password = input("Enter password: ")
role = input("Enter role (admin/teacher/student): ")
conn = connect_db()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO users (username, password, role) VALUES (%s, %s, %s)", (username, password, role))
conn.commit() # Save changes to the database
print(f"User {username} registered successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
conn.close()
# Function to authenticate user
def authenticate_user():
username = input("Enter username: ")
password = input("Enter password: ")
conn = connect_db()
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))
user = cursor.fetchone() # Fetch one record
cursor.close()
conn.close()
return user # Return user details if found
# Function to mark attendance for multiple students
def mark_attendance():
conn = connect_db()
cursor = conn.cursor()
# Fetch all students
cursor.execute("SELECT user_id, username FROM users WHERE role='student'")
students = cursor.fetchall()
print("\nMark Attendance:")
for student in students:
status = input(f"Is {student[1]} present? (P/A): ").strip().upper()
if status not in ['P', 'A']:
print(f"Invalid input for {student[1]}. Skipping...")
continue
status_text = 'Present' if status == 'P' else 'Absent'
date = datetime.now().date() # Get today's date
try:
cursor.execute("INSERT INTO attendance (user_id, date, status) VALUES (%s, %s, %s)",
(student[0], date, status_text))
except mysql.connector.Error as err:
print(f"Error marking attendance for {student[1]}: {err}")
conn.commit() # Save changes to the database
cursor.close()
conn.close()
print("Attendance marked successfully.")
# Function to view attendance records for a specific user
def view_attendance(user_id):
conn = connect_db()
cursor = conn.cursor()
cursor.execute("SELECT date, status FROM attendance WHERE user_id=%s", (user_id,))
records = cursor.fetchall() # Fetch all records
print("\nAttendance Records:")
if not records:
print("No records found.")
for record in records:
print(f"Date: {record[0]}, Status: {record[1]}") # Print each record
cursor.close()
conn.close()
# Function to generate attendance report for a specific time frame
def generate_report():
print("\nSelect report type:")
print("1. Daily")
print("2. Weekly")
print("3. Monthly")
print("4. Yearly")
choice = input("Choose an option: ")
if choice == '1':
date_str = input("Enter date (YYYY-MM-DD): ")
start_date = end_date = date_str
elif choice == '2':
end_date_str = input("Enter end date (YYYY-MM-DD): ")
end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
start_date = end_date - timedelta(days=6) # Last 7 days
elif choice == '3':
month_str = input("Enter month and year (YYYY-MM): ")
start_date = f"{month_str}-01"
end_date = datetime.strptime(start_date, "%Y-%m-%d") + timedelta(days=30)
elif choice == '4':
year_str = input("Enter year (YYYY): ")
start_date = f"{year_str}-01-01"
end_date = f"{year_str}-12-31"
else:
print("Invalid choice.")
return
conn = connect_db()
# Adjust query parameters based on selected report type
query = """
SELECT u.username, a.date, a.status
FROM attendance a
JOIN users u ON a.user_id = u.user_id
WHERE a.date BETWEEN %s AND %s
ORDER BY u.username, a.date """
try:
cursor = conn.cursor()
if choice in ['1', '2']:
cursor.execute(query, (start_date, end_date.strftime("%Y-%m-%d")))
else:
cursor.execute(query, (start_date[:10], end_date[:10]))
records = cursor.fetchall() # Fetch all records
print("\nAttendance Report:")
for record in records:
print(f"Student: {record[0]}, Date: {record[1]}, Status: {record[2]}")
except mysql.connector.Error as err:
print(f"Error generating report: {err}")
finally:
if 'cursor' in locals():
cursor.close() # Close the cursor if it was created
conn.close() # Always close the connection
# Main function to run the application
def main():
while True:
print("\nWelcome to Attendance Management System")
print("1. Login")
print("2. Register")
print("3. Generate Attendance Report")
print("4. Exit")
choice = input("Choose an option: ")
if choice == '1':
user = authenticate_user() # Authenticate user
if user:
user_id, username, _, role = user # Unpack user details
print(f"Welcome {username}! You are logged in as {role}.")
if role == 'admin':
print("Admin functionalities can be added here.")
elif role == 'teacher':
mark_attendance() # Mark attendance for students
elif role == 'student':
view_attendance(user_id) # View own attendance records
else:
print("Invalid credentials.")
elif choice == '2':
register_user() # Register a new user
elif choice == '3':
generate_report() # Generate attendance report
elif choice == '4':
break # Exit the program
if _name_ == "_main_":
main() # Run the main function when script is executed
0 Comments