Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Act as a web developer, using html css and javascript and use backend php.
- ChatGPT said:
- ChatGPT
- Sure! I can help you with a web development project using HTML, CSS, JavaScript, and PHP for the backend. Let’s create a simple example where users can submit a form, and the data is processed using PHP.
- Project Structure
- bash
- Copy code
- /my-website
- │
- ├── index.html
- ├── style.css
- ├── script.js
- └── submit.php
- 1. index.html
- This is the main HTML file where the form will be displayed.
- html
- Copy code
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Simple Form</title>
- </head>
- <body>
- <div class="container">
- <h1>Submit Your Information</h1>
- <form id="myForm" action="submit.php" method="POST">
- <label for="name">Name:</label>
- <input type="text" id="name" name="name" required>
- <br>
- <label for="email">Email:</label>
- <input type="email" id="email" name="email" required>
- <br>
- <input type="submit" value="Submit">
- </form>
- <div id="response"></div>
- </div>
- <script src="script.js"></script>
- </body>
- </html>
- 2. style.css
- Basic styling for the form.
- css
- Copy code
- body {
- font-family: Arial, sans-serif;
- background-color: #f4f4f4;
- margin: 0;
- padding: 20px;
- }
- .container {
- max-width: 400px;
- margin: auto;
- background: white;
- padding: 20px;
- border-radius: 8px;
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
- }
- label {
- display: block;
- margin-bottom: 5px;
- }
- input[type="text"],
- input[type="email"] {
- width: 100%;
- padding: 10px;
- margin-bottom: 15px;
- border: 1px solid #ccc;
- border-radius: 4px;
- }
- input[type="submit"] {
- background: #5cb85c;
- color: white;
- border: none;
- padding: 10px 15px;
- border-radius: 4px;
- cursor: pointer;
- }
- input[type="submit"]:hover {
- background: #4cae4c;
- }
- 3. script.js
- JavaScript to handle form submission and display the response.
- javascript
- Copy code
- document.getElementById('myForm').addEventListener('submit', function(e) {
- e.preventDefault(); // Prevent default form submission
- const formData = new FormData(this);
- fetch('submit.php', {
- method: 'POST',
- body: formData,
- })
- .then(response => response.text())
- .then(data => {
- document.getElementById('response').innerHTML = data;
- document.getElementById('myForm').reset(); // Reset form after submission
- })
- .catch(error => console.error('Error:', error));
- });
- 4. submit.php
- This is the backend PHP file that processes the form data.
- php
- Copy code
- <?php
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
- $name = htmlspecialchars(trim($_POST['name']));
- $email = htmlspecialchars(trim($_POST['email']));
- // Here you could save the data to a database or perform other actions
- echo "Thank you, $name! Your email ($email) has been received.";
- } else {
- echo "Invalid request method.";
- }
- ?>
- How to Run
- Create a directory named my-website.
- Inside this directory, create the four files (index.html, style.css, script.js, and submit.php) and copy the respective code into each file.
- Set up a local server (like XAMPP, WAMP, or MAMP) and place the my-website directory in the server's root directory (e.g., htdocs for XAMPP).
- Open your web browser and navigate to http://localhost/my-website/index.html.
- This simple project allows users to submit their name and email, which are then processed by the PHP backend, and the response is displayed on the page. Let me know if you need any additional features or modifications!
- You said:
- clear
- ChatGPT said:
- ChatGPT
- Got it! If you need any further assistance or have specific questions about web development, feel free to ask!
- You said:
- Act as a web developer, using html css and javascript and use backend php.
- Create a php website that has subject wise book information. New book will be inserted into it. Also give searching facility by subject.(book_code, book_name,
- author_name,subject_name, cost,ISBN NO).
- ChatGPT said:
- ChatGPT
- Sure! Let's create a simple PHP website that allows you to manage book information by subject, including the ability to insert new books and search by subject. We'll structure the project as follows:
- Project Structure
- bash
- Copy code
- /book-library
- │
- ├── index.php
- ├── style.css
- ├── script.js
- └── db.php
- 1. db.php
- This file will handle the database connection.
- php
- Copy code
- <?php
- $host = 'localhost'; // Database host
- $db = 'book_library'; // Database name
- $user = 'root'; // Database username
- $pass = ''; // Database password
- try {
- $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
- $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- } catch (PDOException $e) {
- echo "Connection failed: " . $e->getMessage();
- }
- ?>
- 2. index.php
- This is the main file for displaying and inserting book information.
- php
- Copy code
- <?php
- include 'db.php';
- // Handle form submission
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
- $book_code = htmlspecialchars(trim($_POST['book_code']));
- $book_name = htmlspecialchars(trim($_POST['book_name']));
- $author_name = htmlspecialchars(trim($_POST['author_name']));
- $subject_name = htmlspecialchars(trim($_POST['subject_name']));
- $cost = htmlspecialchars(trim($_POST['cost']));
- $isbn_no = htmlspecialchars(trim($_POST['isbn_no']));
- $stmt = $pdo->prepare("INSERT INTO books (book_code, book_name, author_name, subject_name, cost, isbn_no) VALUES (?, ?, ?, ?, ?, ?)");
- $stmt->execute([$book_code, $book_name, $author_name, $subject_name, $cost, $isbn_no]);
- }
- // Handle search
- $books = [];
- if (isset($_GET['subject_name'])) {
- $subject_name = htmlspecialchars(trim($_GET['subject_name']));
- $stmt = $pdo->prepare("SELECT * FROM books WHERE subject_name = ?");
- $stmt->execute([$subject_name]);
- $books = $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Book Library</title>
- </head>
- <body>
- <div class="container">
- <h1>Book Library</h1>
- <h2>Add New Book</h2>
- <form action="index.php" method="POST">
- <label for="book_code">Book Code:</label>
- <input type="text" id="book_code" name="book_code" required>
- <br>
- <label for="book_name">Book Name:</label>
- <input type="text" id="book_name" name="book_name" required>
- <br>
- <label for="author_name">Author Name:</label>
- <input type="text" id="author_name" name="author_name" required>
- <br>
- <label for="subject_name">Subject Name:</label>
- <input type="text" id="subject_name" name="subject_name" required>
- <br>
- <label for="cost">Cost:</label>
- <input type="number" id="cost" name="cost" required>
- <br>
- <label for="isbn_no">ISBN No:</label>
- <input type="text" id="isbn_no" name="isbn_no" required>
- <br>
- <input type="submit" value="Add Book">
- </form>
- <h2>Search Books by Subject</h2>
- <form action="index.php" method="GET">
- <label for="subject_search">Subject Name:</label>
- <input type="text" id="subject_search" name="subject_name" required>
- <input type="submit" value="Search">
- </form>
- <h2>Book List</h2>
- <table>
- <tr>
- <th>Book Code</th>
- <th>Book Name</th>
- <th>Author Name</th>
- <th>Subject Name</th>
- <th>Cost</th>
- <th>ISBN No</th>
- </tr>
- <?php foreach ($books as $book): ?>
- <tr>
- <td><?php echo $book['book_code']; ?></td>
- <td><?php echo $book['book_name']; ?></td>
- <td><?php echo $book['author_name']; ?></td>
- <td><?php echo $book['subject_name']; ?></td>
- <td><?php echo $book['cost']; ?></td>
- <td><?php echo $book['isbn_no']; ?></td>
- </tr>
- <?php endforeach; ?>
- </table>
- </div>
- </body>
- </html>
- 3. style.css
- Basic styling for the website.
- css
- Copy code
- body {
- font-family: Arial, sans-serif;
- background-color: #f4f4f4;
- margin: 0;
- padding: 20px;
- }
- .container {
- max-width: 800px;
- margin: auto;
- background: white;
- padding: 20px;
- border-radius: 8px;
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
- }
- h1, h2 {
- color: #333;
- }
- label {
- display: block;
- margin-bottom: 5px;
- }
- input[type="text"],
- input[type="number"],
- input[type="submit"] {
- width: 100%;
- padding: 10px;
- margin-bottom: 15px;
- border: 1px solid #ccc;
- border-radius: 4px;
- }
- table {
- width: 100%;
- border-collapse: collapse;
- margin-top: 20px;
- }
- table, th, td {
- border: 1px solid #ddd;
- }
- th, td {
- padding: 10px;
- text-align: left;
- }
- tr:nth-child(even) {
- background-color: #f2f2f2;
- }
- 4. Database Setup
- You will need to create a MySQL database and a table for storing book information. You can run the following SQL commands to set it up:
- sql
- Copy code
- CREATE DATABASE book_library;
- USE book_library;
- CREATE TABLE books (
- id INT AUTO_INCREMENT PRIMARY KEY,
- book_code VARCHAR(50) NOT NULL,
- book_name VARCHAR(255) NOT NULL,
- author_name VARCHAR(255) NOT NULL,
- subject_name VARCHAR(255) NOT NULL,
- cost DECIMAL(10, 2) NOT NULL,
- isbn_no VARCHAR(50) NOT NULL
- );
- How to Run
- Create a directory named book-library.
- Inside this directory, create the four files (index.php, style.css, script.js, and db.php) and copy the respective code into each file.
- Set up a local server (like XAMPP, WAMP, or MAMP) and place the book-library directory in the server's root directory (e.g., htdocs for XAMPP).
- Open your web browser and navigate to http://localhost/book-library/index.php.
- Now you have a simple PHP website where you can insert book information and search for books by subject. If you need any more features or modifications, just let me know!
- You said:
- validation add multiple book_code not be allowed that time show javascript alert
- ChatGPT said:
- ChatGPT
- To ensure that duplicate book codes are not allowed when adding new books, we can implement a validation check using JavaScript. If the user tries to submit a book with a duplicate book code, an alert will be shown.
- Here’s how you can modify the index.php file and add JavaScript to handle this validation.
- Updated index.php
- php
- Copy code
- <?php
- include 'db.php';
- // Initialize an array to hold existing book codes
- $existing_book_codes = [];
- // Fetch existing book codes from the database
- $stmt = $pdo->query("SELECT book_code FROM books");
- while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
- $existing_book_codes[] = $row['book_code'];
- }
- // Handle form submission
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
- $book_code = htmlspecialchars(trim($_POST['book_code']));
- $book_name = htmlspecialchars(trim($_POST['book_name']));
- $author_name = htmlspecialchars(trim($_POST['author_name']));
- $subject_name = htmlspecialchars(trim($_POST['subject_name']));
- $cost = htmlspecialchars(trim($_POST['cost']));
- $isbn_no = htmlspecialchars(trim($_POST['isbn_no']));
- // Check for duplicate book code
- if (in_array($book_code, $existing_book_codes)) {
- $error_message = "This Book Code already exists!";
- } else {
- $stmt = $pdo->prepare("INSERT INTO books (book_code, book_name, author_name, subject_name, cost, isbn_no) VALUES (?, ?, ?, ?, ?, ?)");
- $stmt->execute([$book_code, $book_name, $author_name, $subject_name, $cost, $isbn_no]);
- // Refresh the existing book codes after inserting
- $existing_book_codes[] = $book_code;
- }
- }
- // Handle search
- $books = [];
- if (isset($_GET['subject_name'])) {
- $subject_name = htmlspecialchars(trim($_GET['subject_name']));
- $stmt = $pdo->prepare("SELECT * FROM books WHERE subject_name = ?");
- $stmt->execute([$subject_name]);
- $books = $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Book Library</title>
- <script>
- function validateForm() {
- const existingBookCodes = <?php echo json_encode($existing_book_codes); ?>;
- const bookCode = document.getElementById('book_code').value;
- if (existingBookCodes.includes(bookCode)) {
- alert("This Book Code already exists!");
- return false; // Prevent form submission
- }
- return true; // Allow form submission
- }
- </script>
- </head>
- <body>
- <div class="container">
- <h1>Book Library</h1>
- <h2>Add New Book</h2>
- <form action="index.php" method="POST" onsubmit="return validateForm();">
- <label for="book_code">Book Code:</label>
- <input type="text" id="book_code" name="book_code" required>
- <br>
- <label for="book_name">Book Name:</label>
- <input type="text" id="book_name" name="book_name" required>
- <br>
- <label for="author_name">Author Name:</label>
- <input type="text" id="author_name" name="author_name" required>
- <br>
- <label for="subject_name">Subject Name:</label>
- <input type="text" id="subject_name" name="subject_name" required>
- <br>
- <label for="cost">Cost:</label>
- <input type="number" id="cost" name="cost" required>
- <br>
- <label for="isbn_no">ISBN No:</label>
- <input type="text" id="isbn_no" name="isbn_no" required>
- <br>
- <input type="submit" value="Add Book">
- </form>
- <h2>Search Books by Subject</h2>
- <form action="index.php" method="GET">
- <label for="subject_search">Subject Name:</label>
- <input type="text" id="subject_search" name="subject_name" required>
- <input type="submit" value="Search">
- </form>
- <h2>Book List</h2>
- <table>
- <tr>
- <th>Book Code</th>
- <th>Book Name</th>
- <th>Author Name</th>
- <th>Subject Name</th>
- <th>Cost</th>
- <th>ISBN No</th>
- </tr>
- <?php foreach ($books as $book): ?>
- <tr>
- <td><?php echo $book['book_code']; ?></td>
- <td><?php echo $book['book_name']; ?></td>
- <td><?php echo $book['author_name']; ?></td>
- <td><?php echo $book['subject_name']; ?></td>
- <td><?php echo $book['cost']; ?></td>
- <td><?php echo $book['isbn_no']; ?></td>
- </tr>
- <?php endforeach; ?>
- </table>
- <?php if (isset($error_message)): ?>
- <div class="error"><?php echo $error_message; ?></div>
- <?php endif; ?>
- </div>
- </body>
- </html>
- Key Changes Made:
- JavaScript Validation: Added a JavaScript function validateForm() that checks if the entered book code exists in the existing_book_codes array.
- Dynamic Book Codes: The existing book codes are fetched from the database when the page loads and passed to the JavaScript in JSON format.
- Form Submission: The form now calls validateForm() on submission. If a duplicate book code is detected, an alert will be shown and form submission will be prevented.
- How to Run
- Replace the index.php file in your book-library directory with the updated code.
- Make sure your database is set up as before.
- Refresh your browser to test the new validation feature.
- Now, if you attempt to enter a duplicate book code, an alert will notify you and prevent the form from being submitted. Let me know if you need any more features or adjustments!
- You said:
- search function create using js
- ChatGPT said:
- ChatGPT
- To implement the search functionality using JavaScript, we'll create a client-side search feature that filters the displayed books based on user input without reloading the page. Here’s how you can enhance the existing index.php file to add this feature.
- Updated index.php with JavaScript Search
- php
- Copy code
- <?php
- include 'db.php';
- // Fetch all books for displaying in the table
- $stmt = $pdo->query("SELECT * FROM books");
- $books = $stmt->fetchAll(PDO::FETCH_ASSOC);
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Book Library</title>
- <script>
- function searchBooks() {
- const input = document.getElementById('search_input').value.toLowerCase();
- const rows = document.querySelectorAll('#book_table tbody tr');
- rows.forEach(row => {
- const bookCode = row.cells[0].textContent.toLowerCase();
- const bookName = row.cells[1].textContent.toLowerCase();
- const authorName = row.cells[2].textContent.toLowerCase();
- const subjectName = row.cells[3].textContent.toLowerCase();
- // Check if input matches book code, name, author, or subject
- if (bookCode.includes(input) || bookName.includes(input) || authorName.includes(input) || subjectName.includes(input)) {
- row.style.display = ''; // Show row
- } else {
- row.style.display = 'none'; // Hide row
- }
- });
- }
- </script>
- </head>
- <body>
- <div class="container">
- <h1>Book Library</h1>
- <h2>Add New Book</h2>
- <form action="index.php" method="POST" onsubmit="return validateForm();">
- <label for="book_code">Book Code:</label>
- <input type="text" id="book_code" name="book_code" required>
- <br>
- <label for="book_name">Book Name:</label>
- <input type="text" id="book_name" name="book_name" required>
- <br>
- <label for="author_name">Author Name:</label>
- <input type="text" id="author_name" name="author_name" required>
- <br>
- <label for="subject_name">Subject Name:</label>
- <input type="text" id="subject_name" name="subject_name" required>
- <br>
- <label for="cost">Cost:</label>
- <input type="number" id="cost" name="cost" required>
- <br>
- <label for="isbn_no">ISBN No:</label>
- <input type="text" id="isbn_no" name="isbn_no" required>
- <br>
- <input type="submit" value="Add Book">
- </form>
- <h2>Search Books</h2>
- <input type="text" id="search_input" placeholder="Search by book code, name, author, or subject" onkeyup="searchBooks()">
- <h2>Book List</h2>
- <table id="book_table">
- <thead>
- <tr>
- <th>Book Code</th>
- <th>Book Name</th>
- <th>Author Name</th>
- <th>Subject Name</th>
- <th>Cost</th>
- <th>ISBN No</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($books as $book): ?>
- <tr>
- <td><?php echo htmlspecialchars($book['book_code']); ?></td>
- <td><?php echo htmlspecialchars($book['book_name']); ?></td>
- <td><?php echo htmlspecialchars($book['author_name']); ?></td>
- <td><?php echo htmlspecialchars($book['subject_name']); ?></td>
- <td><?php echo htmlspecialchars($book['cost']); ?></td>
- <td><?php echo htmlspecialchars($book['isbn_no']); ?></td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- </body>
- </html>
- Key Changes Made:
- Search Input: Added an input field for the user to type in their search query.
- JavaScript Function searchBooks: This function retrieves the input value, iterates over the rows of the book table, and checks if the input matches any of the cells (book code, book name, author name, or subject name). If a match is found, the row is displayed; otherwise, it is hidden.
- Dynamic Search: The onkeyup event on the search input triggers the searchBooks function whenever the user types in the input field, allowing for real-time search results.
- How to Run
- Replace the previous index.php code with the updated version above.
- Ensure your database is set up correctly.
- Open your web browser and navigate to http://localhost/book-library/index.php.
- Now, you can search through the list of books in real time based on the entered query! If you have any more questions or need further modifications, feel free to ask!
- You said:
- add pagination
- ChatGPT said:
- ChatGPT
- To add pagination to the book list in your PHP application, you'll need to modify your SQL query to limit the number of results shown per page and create links to navigate between pages. Here’s how you can implement pagination in your index.php file.
- Updated index.php with Pagination
- php
- Copy code
- <?php
- include 'db.php';
- // Set the number of results per page
- $results_per_page = 5;
- // Find the total number of results in the database
- $stmt = $pdo->query("SELECT COUNT(*) FROM books");
- $total_results = $stmt->fetchColumn();
- $total_pages = ceil($total_results / $results_per_page); // Calculate total pages
- // Get the current page number from URL, default is 1
- $current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
- $current_page = max(1, min($current_page, $total_pages)); // Ensure it's a valid page number
- // Calculate the starting limit for the SQL query
- $starting_limit = ($current_page - 1) * $results_per_page;
- // Fetch books for the current page
- $stmt = $pdo->prepare("SELECT * FROM books LIMIT ?, ?");
- $stmt->bindParam(1, $starting_limit, PDO::PARAM_INT);
- $stmt->bindParam(2, $results_per_page, PDO::PARAM_INT);
- $stmt->execute();
- $books = $stmt->fetchAll(PDO::FETCH_ASSOC);
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Book
- You said:
- add pagination using js
- ChatGPT said:
- ChatGPT
- To implement pagination using JavaScript, we'll need to manage the displayed books on the client side. This approach involves fetching all book data at once and then creating a JavaScript function to handle the pagination. Below is how you can modify your existing setup to include client-side pagination.
- Updated index.php with JavaScript Pagination
- Here's the complete code for index.php that incorporates pagination using JavaScript:
- php
- Copy code
- <?php
- include 'db.php';
- // Fetch all books for displaying in the table
- $stmt = $pdo->query("SELECT * FROM books");
- $books = $stmt->fetchAll(PDO::FETCH_ASSOC);
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Book Library</title>
- <script>
- let currentPage = 1;
- const resultsPerPage = 5;
- function displayBooks() {
- const bookTableBody = document.getElementById('book_table_body');
- const totalBooks = <?php echo count($books); ?>;
- const totalPages = Math.ceil(totalBooks / resultsPerPage);
- // Clear the table body
- bookTableBody.innerHTML = '';
- // Calculate start and end indexes for the current page
- const startIndex = (currentPage - 1) * resultsPerPage;
- const endIndex = Math.min(startIndex + resultsPerPage, totalBooks);
- // Populate the table with books for the current page
- for (let i = startIndex; i < endIndex; i++) {
- const book = <?php echo json_encode($books); ?>[i];
- const row = `
- <tr>
- <td>${book.book_code}</td>
- <td>${book.book_name}</td>
- <td>${book.author_name}</td>
- <td>${book.subject_name}</td>
- <td>${book.cost}</td>
- <td>${book.isbn_no}</td>
- </tr>
- `;
- bookTableBody.innerHTML += row;
- }
- // Update pagination controls
- updatePaginationControls(totalPages);
- }
- function updatePaginationControls(totalPages) {
- const paginationControls = document.getElementById('pagination_controls');
- paginationControls.innerHTML = '';
- for (let i = 1; i <= totalPages; i++) {
- const button = document.createElement('button');
- button.innerText = i;
- button.className = 'pagination-button';
- button.onclick = function() {
- currentPage = i;
- displayBooks();
- };
- if (i === currentPage) {
- button.classList.add('active');
- }
- paginationControls.appendChild(button);
- }
- }
- window.onload = displayBooks; // Display books on page load
- </script>
- </head>
- <body>
- <div class="container">
- <h1>Book Library</h1>
- <h2>Add New Book</h2>
- <form action="index.php" method="POST" onsubmit="return validateForm();">
- <label for="book_code">Book Code:</label>
- <input type="text" id="book_code" name="book_code" required>
- <br>
- <label for="book_name">Book Name:</label>
- <input type="text" id="book_name" name="book_name" required>
- <br>
- <label for="author_name">Author Name:</label>
- <input type="text" id="author_name" name="author_name" required>
- <br>
- <label for="subject_name">Subject Name:</label>
- <input type="text" id="subject_name" name="subject_name" required>
- <br>
- <label for="cost">Cost:</label>
- <input type="number" id="cost" name="cost" required>
- <br>
- <label for="isbn_no">ISBN No:</label>
- <input type="text" id="isbn_no" name="isbn_no" required>
- <br>
- <input type="submit" value="Add Book">
- </form>
- <h2>Search Books</h2>
- <input type="text" id="search_input" placeholder="Search by book code, name, author, or subject" onkeyup="searchBooks()">
- <h2>Book List</h2>
- <table id="book_table">
- <thead>
- <tr>
- <th>Book Code</th>
- <th>Book Name</th>
- <th>Author Name</th>
- <th>Subject Name</th>
- <th>Cost</th>
- <th>ISBN No</th>
- </tr>
- </thead>
- <tbody id="book_table_body">
- <!-- Books will be inserted here by JavaScript -->
- </tbody>
- </table>
- <div id="pagination_controls" class="pagination"></div>
- </div>
- </body>
- </html>
- Key Changes Made:
- JavaScript Logic:
- Pagination Variables: Added currentPage and resultsPerPage to manage pagination.
- displayBooks Function: This function calculates which books to show based on the current page and updates the table accordingly.
- updatePaginationControls Function: This creates pagination buttons based on the total number of pages.
- onload Event: Calls displayBooks() to populate the table when the page loads.
- HTML Table: The table body (<tbody id="book_table_body">) is dynamically populated by JavaScript instead of being rendered server-side.
- Pagination Controls: Added a <div id="pagination_controls"> to hold the pagination buttons, which are generated dynamically based on the number of total pages.
- How to Run
- Replace your existing index.php code with the updated version above.
- Ensure your database is properly set up and contains data.
- Open your web browser and navigate to http://localhost/book-library/index.php.
- With these changes, you should now have a fully functional client-side pagination system that allows users to navigate through pages of books without reloading the page. If you have any questions or need further adjustments, feel free to ask!
- You said:
- add serial no in table
- ChatGPT said:
- ChatGPT
- To add a serial number (S.No.) column to your book list table, you can easily do this by adjusting the JavaScript that populates the table. The serial number will be calculated based on the current page and the number of results per page.
- Here’s how you can modify the index.php file to include a serial number column:
- Updated index.php with Serial Number
- php
- Copy code
- <?php
- include 'db.php';
- // Fetch all books for displaying in the table
- $stmt = $pdo->query("SELECT * FROM books");
- $books = $stmt->fetchAll(PDO::FETCH_ASSOC);
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="style.css">
- <title>Book Library</title>
- <script>
- let currentPage = 1;
- const resultsPerPage = 5;
- function displayBooks() {
- const bookTableBody = document.getElementById('book_table_body');
- const totalBooks = <?php echo count($books); ?>;
- const totalPages = Math.ceil(totalBooks / resultsPerPage);
- // Clear the table body
- bookTableBody.innerHTML = '';
- // Calculate start and end indexes for the current page
- const startIndex = (currentPage - 1) * resultsPerPage;
- const endIndex = Math.min(startIndex + resultsPerPage, totalBooks);
- // Populate the table with books for the current page
- for (let i = startIndex; i < endIndex; i++) {
- const book = <?php echo json_encode($books); ?>[i];
- const serialNumber = startIndex + i + 1; // Serial number calculation
- const row = `
- <tr>
- <td>${serialNumber}</td>
- <td>${book.book_code}</td>
- <td>${book.book_name}</td>
- <td>${book.author_name}</td>
- <td>${book.subject_name}</td>
- <td>${book.cost}</td>
- <td>${book.isbn_no}</td>
- </tr>
- `;
- bookTableBody.innerHTML += row;
- }
- // Update pagination controls
- updatePaginationControls(totalPages);
- }
- function updatePaginationControls(totalPages) {
- const paginationControls = document.getElementById('pagination_controls');
- paginationControls.innerHTML = '';
- for (let i = 1; i <= totalPages; i++) {
- const button = document.createElement('button');
- button.innerText = i;
- button.className = 'pagination-button';
- button.onclick = function() {
- currentPage = i;
- displayBooks();
- };
- if (i === currentPage) {
- button.classList.add('active');
- }
- paginationControls.appendChild(button);
- }
- }
- window.onload = displayBooks; // Display books on page load
- </script>
- </head>
- <body>
- <div class="container">
- <h1>Book Library</h1>
- <h2>Add New Book</h2>
- <form action="index.php" method="POST" onsubmit="return validateForm();">
- <label for="book_code">Book Code:</label>
- <input type="text" id="book_code" name="book_code" required>
- <br>
- <label for="book_name">Book Name:</label>
- <input type="text" id="book_name" name="book_name" required>
- <br>
- <label for="author_name">Author Name:</label>
- <input type="text" id="author_name" name="author_name" required>
- <br>
- <label for="subject_name">Subject Name:</label>
- <input type="text" id="subject_name" name="subject_name" required>
- <br>
- <label for="cost">Cost:</label>
- <input type="number" id="cost" name="cost" required>
- <br>
- <label for="isbn_no">ISBN No:</label>
- <input type="text" id="isbn_no" name="isbn_no" required>
- <br>
- <input type="submit" value="Add Book">
- </form>
- <h2>Search Books</h2>
- <input type="text" id="search_input" placeholder="Search by book code, name, author, or subject" onkeyup="searchBooks()">
- <h2>Book List</h2>
- <table id="book_table">
- <thead>
- <tr>
- <th>S.No.</th>
- <th>Book Code</th>
- <th>Book Name</th>
- <th>Author Name</th>
- <th>Subject Name</th>
- <th>Cost</th>
- <th>ISBN No</th>
- </tr>
- </thead>
- <tbody id="book_table_body">
- <!-- Books will be inserted here by JavaScript -->
- </tbody>
- </table>
- <div id="pagination_controls" class="pagination"></div>
- </div>
- </body>
- </html>
- Key Changes Made:
- S.No. Column: Added a new <th>S.No.</th> in the table header.
- Serial Number Calculation: In the displayBooks() function, calculated the serial number based on the current page and index, using:
- javascript
- Copy code
- const serialNumber = startIndex + i + 1; // Serial number calculation
- Updated Row Structure: Included the serial number in the row template.
- How to Run
- Replace your existing index.php code with the updated version above.
- Ensure your database is properly set up and contains data.
- Open your web browser and navigate to http://localhost/book-library/index.php.
- Now, each row in the book list will display a serial number, making it easier to reference books in the list. If you need further modifications or additional features, let me know!
- ChatGPT can make mistakes. Check important info.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement