Library Management System using PHP
Semester: 1 Duration: 90 minutes Total Marks: 20
Database Setup
- Create and use the database
CREATE DATABASE library_db; USE library_db; - Create the
bookstableCREATE TABLE books ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL UNIQUE, author VARCHAR(150) NOT NULL, published_year INT CHECK (published_year > 0), copies INT CHECK (copies >= 1) ); - Create the
loanstableCREATE TABLE loans ( id INT AUTO_INCREMENT PRIMARY KEY, book_id INT NOT NULL, borrower VARCHAR(100) NOT NULL, loan_date DATE DEFAULT (CURDATE()), FOREIGN KEY (book_id) REFERENCES books(id) ON DELETE RESTRICT ); - Insert sample data
INSERT INTO books (title, author, published_year, copies) VALUES ('1984', 'George Orwell', 1949, 5), ('Clean Code', 'Robert C. Martin', 2008, 3), ('The Pragmatic Programmer', 'Andrew Hunt', 1999, 4); INSERT INTO loans (book_id, borrower) VALUES (1, 'Nguyen Van A'), (3, 'Tran Thi B');
Question 1: Display Book List with Sorting (5 marks)
- (3 marks) Fetch and display all records from the
bookstable, sorted bypublished_yearin descending order. - (1 mark) Include an “Add Book” button or link that navigates to
add_book.php. - (1 mark) Next to each book, provide an “Edit” link to
edit_book.phppassing the book’sidas a URL parameter (e.g.,?id=2).
Question 2: Adding a New Book (5 marks)
In add_book.php:
- (1.5 marks) Build an HTML form to input
title,author,published_year, andcopies. - (0.5 marks) Validate that
titleis unique (no duplicates in the database). - (0.5 marks) Validate that
published_yearis greater than 0. - (0.5 marks) Validate that
copiesis at least 1. - (2 marks) If all validations pass, insert the new record into the
bookstable.
Question 3: Editing a Book (5 marks)
In edit_book.php:
- (2 marks) Load the existing book data based on the
idparameter and pre-fill an HTML form withtitle,author,published_year, andcopies. - (0.5 marks) Validate that the updated
titleremains unique, excluding the current record. - (0.5 marks) Validate that
published_year> 0 andcopies≥ 1. - (0.5 marks) Verify that the given
idexists before attempting the update; if not, show an error or redirect. - (1.5 marks) Update the record in the
bookstable when all validations succeed.
Question 4: Deleting a Book (5 marks)
- (1 mark) On the main listing page, add a “Delete” button next to each book.
- (1 mark) Use JavaScript
confirm("Are you sure you want to delete this book?")before deletion. - (1 mark) If the book has existing entries in the
loanstable, prevent deletion and alert “Cannot delete because the book is on loan!”. - (2 marks) If there are no related loans, delete the record from the
bookstable.