Database Interactions
Table of Content:
Database Interactions
Objective: Fetch data from a database using PHP and update the web page asynchronously with AJAX.
Database Configuration (config.php):
connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
HTML (index.html):
Database Interactions Example
PHP (get-data.php):
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 = '
- ';
for (var i = 0; i < data.length; i++) {
output += '
- ' + data[i].column1 + ' - ' + data[i].column2 + ' '; } 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.