Module 5: MySQL වෙතින් Live Data ප්‍රදර්ශනය කිරීම

සරල text පණිවිඩ වෙනුවට, අපගේ දත්ත සමුදායෙන් (database) සැබෑ දත්ත ලබාගෙන ඒවා වෙබ් පිටුවේ live ලෙස පෙන්වමු.

1. Database එකට Connect වීම

පළමුව, අපගේ PHP කේතයට database එක සමඟ සම්බන්ධ වීමට ක්‍රමයක් අවශ්‍යයි. මේ සඳහා අපි වෙනම connection file එකක් සාදමු. මෙය හොඳ පුරුද්දක් වන්නේ, database details (username, password) එක තැනක තබාගැනීමට සහ අවශ්‍ය සෑම තැනකම නැවත නැවත code නොලියා `include` කිරීමට හැකිවන නිසාය.

ඔබගේ project folder එකේ (live-crud-ajax), db.php නමින් අලුත් file එකක් සාදා පහත PHP කේතය ඇතුලත් කරන්න.

<?php

$host = 'localhost';    // Database host
$dbname = 'ajax_course_db'; // Database name (Module 2 හි සෑදූ එක)
$username = 'root';       // Database username (XAMPP default)
$password = '';           // Database password (XAMPP default is empty)

try {
    // Create a new PDO instance
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
} catch (PDOException $e) {
    // If connection fails, stop the script and show an error
    die("Connection failed: " . $e->getMessage());
}

?>

2. දත්ත ලබාගැනීමට `fetch-data.php` වෙනස් කිරීම

දැන් අපගේ fetch-data.php file එක, database එකෙන් දත්ත ලබාගෙන ඒවා **JSON (JavaScript Object Notation)** format එකෙන් response එක ලෙස යවන ලෙස වෙනස් කරමු. JSON යනු Ajax වලදී දත්ත හුවමාරු කරගැනීමට බහුලවම භාවිතා වන සැහැල්ලු format එකකි.

fetch-data.php file එකේ ඇති සියල්ල මකා දමා, පහත කේතය ඇතුලත් කරන්න.

<?php

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

// 2. Prepare and execute the SQL query to get all users
$stmt = $pdo->query("SELECT id, name, email, created_at FROM users ORDER BY id DESC");

// 3. Fetch all results into an associative array
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

// 5. Encode the array into a JSON string and echo it
echo json_encode($users);

?>

3. JSON දත්ත පෙන්වීමට JavaScript එක Update කිරීම

දැන් server එකෙන් එන්නේ JSON data නිසා, අපේ JavaScript කේතයට එම JSON එක කියවා, HTML table එකක් බවට පත්කිරීමට උපදෙස් දිය යුතුය. test-ajax.html file එකේ ඇති JavaScript කේතය සම්පූර්ණයෙන්ම මකා දමා, පහත අලුත් කේතය ඇතුලත් කරන්න.

document.getElementById('loadDataBtn').addEventListener('click', function() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'fetch-data.php', true);

    xhr.onload = function() {
        if (this.status === 200) {
            // 1. Parse the JSON string into a JavaScript object
            const users = JSON.parse(this.responseText);
            
            // 2. Prepare the HTML for the table
            let output = `
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Registered On</th>
                        </tr>
                    </thead>
                    <tbody>`;

            // 3. Loop through the users and add a table row for each
            users.forEach(function(user) {
                output += `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.name}</td>
                        <td>${user.email}</td>
                        <td>${user.created_at}</td>
                    </tr>`;
            });

            // 4. Close the table tags and display the result
            output += '</tbody></table>';
            document.getElementById('responseDiv').innerHTML = output;

        } else {
            document.getElementById('responseDiv').innerHTML = 'Error fetching data.';
        }
    };
    xhr.send();
});

සැලකිය යුතුයි: ඔබගේ `users` table එකේ දත්ත නොමැති නම්, ඔබට හිස් table එකක් පෙනෙනු ඇත. phpMyAdmin වෙත ගොස්, `users` table එකේ "Insert" tab එක මගින් users ලා කිහිප දෙනෙක් ඇතුලත් කර නැවත උත්සාහ කරන්න.