Doing a Search using JavaScript and PHP

Here is one way to do a search on a database table

'use strict';
//edit_blog.js
(function () {
    document.addEventListener("DOMContentLoaded", function () {
        const searchForm = document.getElementById("searchForm");
        const editForm = document.getElementById("data_entry_form");
        const idInput = document.getElementById("id");
        const image_for_edit_record = document.getElementById("image_for_edited_record");
        const category = document.getElementById("category");
        const heading = document.querySelector('.heading');
        const content = document.getElementById("content");
        const resultInput = document.getElementById("searchTerm");

        const headingDropdown = document.querySelector('select[name="heading"]');

        async function displayRecord(searchTerm = null, selectedHeading = null) {
            const requestData = {};
            if(searchTerm !== null) requestData.searchTerm = searchTerm;
            if(selectedHeading !== null) requestData.heading = selectedHeading;

            try {
                const response = await fetch("search_blog_records.php", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(requestData),
                });

                const data = await response.json();
                console.log(data); // Add this line
                if (data.message) {
                    resultInput.value = '';
                    resultInput.placeholder = data.message;
                } else if (data.error) {
                    console.error(data.error);
                } else {
                    const row = data[0];
                    console.log(row);
                    idInput.value = row.id;
                    image_for_edit_record.src = row.thumb_path;
                    image_for_edit_record.alt = row.heading;
                    category.value = row.category;
                    category.textContent = `${row.category.charAt(0).toUpperCase()}${row.category.slice(1)}`;
                    heading.value = row.heading;
                    content.value = row.content;
                }
            } catch (error) {
                console.error("Error:", error);
            }
        }

        searchForm.addEventListener("submit", function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();

            // Get the value of the search term input field and the select box
            const searchTermInput = document.getElementById("searchTerm").value;
            const selectedHeading = document.querySelector('select[name="heading"]').value;

            // Use the input value if it's not empty, otherwise use the select value
            const searchTerm = searchTermInput !== "" ? searchTermInput : null;
            const heading = selectedHeading !== "" ? selectedHeading : null;

            // Call the displayRecord function with the search term and selected heading
            displayRecord(searchTerm, heading);
        });


        // New event listener for the dropdown change
        headingDropdown.addEventListener("change", function() {
            const selectedHeading = headingDropdown.options[headingDropdown.selectedIndex].value;
            displayRecord(null, selectedHeading);
        });

        // Add an event listener to the edit form's submit event
        editForm.addEventListener("submit", async function (event) {
            // Prevent the default form submit behavior
            event.preventDefault();

            // Create a FormData object from the edit form
            const formData = new FormData(editForm);
            //console.log("form data", formData);
            // Send a POST request to the edit_update_blog.php endpoint with the form data
            const response = await fetch("edit_update_blog.php", {
                method: "POST",
                body: formData,
            });

            // Check if the request was successful
            if (response.ok) {
                const result = await response.json();
                console.log(result);
                // If the response has a "success" property and its value is true, clear the form
                if (result.success) {
                    resultInput.value = '';          // Clear the current value of the search input field
                    resultInput.placeholder = "New Search"; // Set the placeholder to `New Search`
                    image_for_edit_record.src = "";
                    image_for_edit_record.alt = "";
                    editForm.reset(); // Resetting the edit form
                    searchForm.reset(); // Resetting the search form

                    // Reset select box to default (first) option
                    const selectBox = document.querySelector('select[name="heading"]');
                    selectBox.selectedIndex = 0;
                }

            } else {
                console.error(
                    "Error submitting the form:",
                    response.status,
                    response.statusText
                );
                // Handle error response
            }
        });


    });
})();

and the PHP

<?php

// Send a response to the client with the content type set to application/json.
header('Content-Type: application/json');

// Include the necessary files and classes for this script.
require_once 'assets/config/config.php';
require_once "vendor/autoload.php";

// Use some classes for error handling, database connection and login-related actions.
use PhotoTech\ErrorHandler;
use PhotoTech\Database;
use PhotoTech\LoginRepository as Login;

// Instantiate an ErrorHandler object.
$errorHandler = new ErrorHandler();

// Set a custom exception handler function.
set_exception_handler([$errorHandler, 'handleException']);

// Create a new Database object and establish a PDO connection.
$database = new Database();
$pdo = $database->createPDO();

// Instantiate a Login object.
$login = new Login($pdo);

// Main try-catch block.
try {
    // Get the request body and decode it as JSON.
    $request = json_decode(file_get_contents('php://input'), true);

    // Extract the search term and heading from the request, if they exist.
    $searchTerm = isset($request['searchTerm']) ? $request['searchTerm'] : null;
    $heading = isset($request['heading']) ? $request['heading'] : null;

    // If a search term was provided, use a full-text search on the 'content' field.
    // Before this can work, you'll need to make sure your content column is indexed for full-text searching.
    // You can do this with the following SQL command:
    // Example:
    // ALTER TABLE gallery ADD FULLTEXT(content);
    if($searchTerm !== null) {
        $sql = "SELECT * FROM gallery WHERE MATCH(content) AGAINST(:searchTerm IN NATURAL LANGUAGE MODE) LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':searchTerm', $searchTerm);

        // If a heading was provided, search for exact matches on the 'heading' field.
    } else if($heading !== null) {
        $sql = "SELECT * FROM gallery WHERE heading = :heading LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':heading', $heading);

        // If neither a search term nor a heading was provided, throw an exception.
    } else {
        throw new Exception("No valid search term or heading provided");
    }

    // Execute the prepared statement.
    $stmt->execute();

    // Fetch the results and handle them as needed.
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If results were found, return them to the client as JSON.
    if ($results) {
        echo json_encode($results);
    } else {
        echo json_encode(['message' => 'No results found.']);
    }

// Catch any exceptions that occur during database interaction.
} catch (PDOException $e) {
    echo json_encode(['error' => $e->getMessage()]);
}

Sponsor our Newsletter | Privacy Policy | Terms of Service