Table of Contents

    Database Interactions

    Database Interactions

    Objective: Fetch data from a database using PHP and update the web page asynchronously with AJAX.

    Database Configuration (config.php):

    
    <?php
    // config.php - Database configuration
    $host = "localhost";
    $username = "your_username";
    $password = "your_password";
    $database = "your_database";
    
    // Create connection
    $conn = new mysqli($host, $username, $password, $database);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    ?>
    
    

    HTML (index.html):

    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Database Interactions Example</title>
        <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
        <script src="database-script.js"></script>
    </head>
    <body>
        <div id="dynamic-data-container">
            <!-- Database data will be loaded here -->
        </div>
        <button onclick="loadDataFromDatabase()">Load Data</button>
    </body>
    </html>
    
    

     

    PHP (get-data.php):

    
    <?php
    // get-data.php - Fetch data from the database
    include("config.php");
    
    $sql = "SELECT * FROM your_table";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        // Output data in JSON format
        $data = array();
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        echo json_encode($data);
    } else {
        echo "No data found";
    }
    
    $conn->close();
    ?>
    
    

    JavaScript (database-script.js):

    
    function loadDataFromDatabase() {
        // Using jQuery for AJAX request
        $.ajax({
            url: 'get-data.php',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                // Update the content container with the retrieved data
                displayData(response);
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }
    
    function displayData(data) {
        // Display the data on the page
        var output = '<ul>';
        for (var i = 0; i < data.length; i++) {
            output += '<li>' + data[i].column1 + ' - ' + data[i].column2 + '</li>';
        }
        output += '</ul>';
        
        $('#dynamic-data-container').html(output);
    }
    
    

     

    Explanation:

    • Clicking the "Load Data" button triggers the loadDataFromDatabase JavaScript function.
    • The function makes an AJAX request to get-data.php, which fetches data from the database.
    • The PHP file retrieves data from the database and returns it in JSON format.
    • The JavaScript function updates the content container with the received data without refreshing the entire page.

    This example illustrates how PHP can interact with a database to fetch data, and AJAX helps in updating specific parts of the page asynchronously. The retrieved data is displayed on the web page without the need for a full page reload, providing a seamless user experience.