Module 6: Live Search පහසුකමක් ගොඩනැගීම

පරිශීලකයා ටයිප් කරන විටම database එකෙන් දත්ත සොයා real-time ලෙස ප්‍රතිඵල පෙන්වන search box එකක් සාදමු.

1. Search Interface එක සෑදීම (HTML)

Live Search feature එක සඳහා අපි අලුත් HTML file එකක් නිර්මාණය කරමු. ඔබගේ project folder එකේ, live-search.html නමින් අලුත් file එකක් සාදා පහත HTML කේතය ඇතුලත් කරන්න.

<!DOCTYPE html>
<html lang="si">
<head>
    <title>Live User Search</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-5">
    <h1>Live User Search</h1>
    <p>Start typing a name in the search box below:</p>
    
    <input type="text" id="searchBox" class="form-control" placeholder="Search for names...">
    
    <div id="resultsDiv" class="mt-4"></div>

    <script src="search-script.js"></script>
</body>
</html>

සැලකිය යුතුයි: මෙහිදී අපි JavaScript කේතය වෙනම file එකක (search-script.js) තබමු. මෙය කේතය සංවිධානය කර තබාගැනීමට හොඳ ක්‍රමයකි.


2. Live Search සඳහා JavaScript කේතය

දැන්, search-script.js නමින් අලුත් JavaScript file එකක් සාදා පහත කේතය ඇතුලත් කරන්න. පරිශීලකයා search box එකේ යමක් ටයිප් කරන සෑම විටම මෙම කේතය ක්‍රියාත්මක වේ.

// Wait for the document to load before running the script
document.addEventListener('DOMContentLoaded', function() {

    const searchBox = document.getElementById('searchBox');
    const resultsDiv = document.getElementById('resultsDiv');

    // Add an event listener that fires on each key press
    searchBox.addEventListener('keyup', function() {
        const searchTerm = searchBox.value;

        // If the search box is empty, clear the results
        if (searchTerm.trim() === '') {
            resultsDiv.innerHTML = '';
            return; // Stop the function
        }

        // Create an Ajax request
        const xhr = new XMLHttpRequest();
        
        // Send the search term to a new PHP file called search.php
        xhr.open('GET', 'search.php?query=' + encodeURIComponent(searchTerm), true);

        xhr.onload = function() {
            if (this.status === 200) {
                const users = JSON.parse(this.responseText);
                let output = '';

                if (users.length > 0) {
                    output = `<table class="table table-striped table-bordered">
                                <thead><tr><th>ID</th><th>Name</th><th>Email</th></tr></thead>
                                <tbody>`;
                    users.forEach(function(user) {
                        output += `<tr>
                                    <td>${user.id}</td>
                                    <td>${user.name}</td>
                                    <td>${user.email}</td>
                                   </tr>`;
                    });
                    output += '</tbody></table>';
                } else {
                    output = '<div class="alert alert-warning">No users found.</div>';
                }
                resultsDiv.innerHTML = output;
            }
        };
        xhr.send();
    });
});

3. Search Logic එක සඳහා PHP Backend එක

JavaScript වෙතින් එවන search term එක භාරගෙන, database එකෙන් ගැලපෙන දත්ත සොයා ආපසු යැවීමට අපට අලුත් PHP file එකක් අවශ්‍යයි. search.php නමින් අලුත් file එකක් සාදා පහත කේතය ඇතුලත් කරන්න.

<?php
// Include the database connection file
require_once 'db.php';

$searchTerm = '';

// Check if the 'query' GET parameter exists
if (isset($_GET['query'])) {
    // Sanitize the input to prevent issues
    $searchTerm = trim($_GET['query']);
}

// Prepare the SQL statement to prevent SQL injection
// The LIKE clause with '%' wildcards finds partial matches
$sql = "SELECT id, name, email FROM users WHERE name LIKE ? ORDER BY name ASC";

$stmt = $pdo->prepare($sql);

// Bind the search term to the placeholder and add wildcards
$stmt->execute(['%' . $searchTerm . '%']);

// Fetch all matching users
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Set the content type header to JSON
header('Content-Type: application/json');

// Encode the results as a JSON string and output it
echo json_encode($users);

?>

⚠️ ඉතා වැදගත්: මෙහිදී අපි Prepared Statements ($pdo->prepare, $stmt->execute) භාවිතා කරමු. මෙය SQL Injection නම්වූ hacking ප්‍රහාර වලින් ඔබගේ database එක ආරක්ෂා කරගැනීමට අත්‍යවශ්‍ය වේ.