prepare("SELECT id FROM books WHERE title = :title AND author_name = :author_name"); $stmt->execute(['title' => $title, 'author_name' => $author_name]); $book = $stmt->fetch(); if ($book) { $book_id = $book['id']; } else { // Insert new book $stmt = db()->prepare("INSERT INTO books (title, author_name, added_by_user_id) VALUES (:title, :author_name, :user_id)"); $stmt->execute(['title' => $title, 'author_name' => $author_name, 'user_id' => $user_id]); $book_id = db()->lastInsertId(); } // Check if the book is already in the user's library $stmt = db()->prepare("SELECT * FROM user_libraries WHERE user_id = :user_id AND book_id = :book_id"); $stmt->execute(['user_id' => $user_id, 'book_id' => $book_id]); if ($stmt->fetch()) { $message = '
This book is already in your library.
'; } else { // Add book to user's library $stmt = db()->prepare("INSERT INTO user_libraries (user_id, book_id) VALUES (:user_id, :book_id)"); $stmt->execute(['user_id' => $user_id, 'book_id' => $book_id]); $message = '
Book added to your library!
'; } } catch (PDOException $e) { $message = '
Error: ' . $e->getMessage() . '
'; } } else { $message = '
Please enter both title and author.
'; } } // Fetch user's books $stmt = db()->prepare("SELECT b.id, b.title, b.author_name FROM books b JOIN user_libraries ul ON b.id = ul.book_id WHERE ul.user_id = :user_id ORDER BY b.title"); $stmt->execute(['user_id' => $user_id]); $user_books = $stmt->fetchAll(); ?>

My Library

Welcome, !

Add a New Book Manually

You can also search and add books automatically.

Your Books
0): ?>
  • by

You haven't added any books yet.