Module 8: Live Data Update කිරීම

පවතින දත්තයක් edit කිරීමට, Bootstrap Modal එකක් භාවිතා කර, වෙනස්කම් පිටුව refresh නොකර database එකේ save කරමු.

1. Update Interface එක (HTML Table & Modal)

මෙම ක්‍රියාවලිය සඳහා, අපට users ලා පෙන්වන table එකක් සහ user කෙනෙකුගේ දත්ත edit කිරීමට pop-up වන modal form එකක් අවශ්‍ය වේ.

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

<!DOCTYPE html>
<html lang="si">
<head>
    <title>Live Data Update</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>User Management</h1>
    <p>Click the "Edit" button on any row to update user details.</p>

    <!-- Div to show success/error messages -->
    <div id="messageDiv"></div>

    <!-- Div where the user table will be displayed -->
    <div id="userTableDiv">Loading users...</div>

    <!-- Bootstrap Modal for Editing -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <!-- Hidden field to store user ID -->
                        <input type="hidden" id="editUserId">
                        <div class="mb-3">
                            <label for="editName" class="form-label">Name</label>
                            <input type="text" id="editName" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label for="editEmail" class="form-label">Email</label>
                            <input type="email" id="editEmail" class="form-control" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="saveChangesBtn" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="update-script.js"></script>
</body>
</html>

2. Update ක්‍රියාවලිය සඳහා JavaScript

මෙම JavaScript කේතය මගින් users ලා පෙන්වීම, Edit බොත්තමක් click කලවිට අදාල user ගේ දත්ත ගෙන modal එක පෙන්වීම, සහ modal එකේ දත්ත save කිරීම පාලනය කරයි. update-script.js නමින් අලුත් file එකක් සාදා පහත කේතය ඇතුලත් කරන්න.

document.addEventListener('DOMContentLoaded', function() {
    const userTableDiv = document.getElementById('userTableDiv');
    const messageDiv = document.getElementById('messageDiv');
    const editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
    const editUserForm = document.getElementById('editUserForm');
    const saveChangesBtn = document.getElementById('saveChangesBtn');

    // --- Function to fetch and display all users ---
    function fetchUsers() {
        /* This function fetches all users from fetch-data.php and displays them in a table.
           Each row will have an Edit button with a data-id attribute containing the user's ID. */
        // ... (This code is similar to Module 7's fetchUsers function)
    }

    // --- Event listener for clicking the "Edit" button (using event delegation) ---
    userTableDiv.addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-edit')) {
            const userId = e.target.getAttribute('data-id');
            // Fetch the specific user's data from a new PHP file
            // Populate the modal form with the data
            // Show the modal
        }
    });

    // --- Event listener for the "Save Changes" button in the modal ---
    saveChangesBtn.addEventListener('click', function() {
        // Get data from the modal form
        // Send data to a new update-data.php file via POST Ajax request
        // On success, hide the modal, show a success message, and refresh the user table
    });

    // --- Initial fetch of users when the page loads ---
    fetchUsers();
});

3. දත්ත Update කරන PHP Backend එක

Modal form එකෙන් එවන දත්ත භාරගෙන, database එකේ අදාල user ගේ record එක update කිරීමට අපට PHP script එකක් අවශ්‍යයි. update-data.php නමින් අලුත් file එකක් සාදා පහත කේතය ඇතුලත් කරන්න.

<?php
require_once 'db.php'; // Include database connection
$response = ['status' => 'error', 'message' => 'An error occurred.'];

if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])) {
    $id = $_POST['id'];
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);

    // ... (Add validation for name and email)

    try {
        // Prepare SQL to prevent SQL injection
        $sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$name, $email, $id])) {
            $response['status'] = 'success';
            $response['message'] = 'User updated successfully!';
        } else {
            $response['message'] = 'Failed to execute update.';
        }
    } catch (PDOException $e) {
        // ... (Handle potential errors like duplicate email)
        $response['message'] = 'Database error: ' . $e->getMessage();
    }
} else {
    $response['message'] = 'Invalid request or missing user ID.';
}

header('Content-Type: application/json');
echo json_encode($response);
?>

4. එක් User කෙනෙකුගේ දත්ත ලබාගැනීමේ PHP Script එක

Edit බොත්තම click කල විට, modal එකට දත්ත පිරවීමට පෙර, එම user ගේ දත්ත database එකෙන් ලබාගත යුතුය. ඒ සඳහා get-user.php නමින් තවත් PHP file එකක් සාදන්න.

<?php
require_once 'db.php';

$user = null;
if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $sql = "SELECT id, name, email FROM users WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
}

header('Content-Type: application/json');
echo json_encode($user);
?>