The JavaScript Fetch API allows web pages to request data asynchronously from a PHP backend that reads records from a MySQL database. This technique avoids page reloads and enables dynamic UI updates using JSON data.
The Fetch API sends an HTTP request to a PHP script. PHP connects to MySQL, retrieves records, converts them to JSON using json_encode(), and sends the response back to JavaScript. JavaScript then parses and renders the data dynamically.
<!-- fetch-data.html: Fetch and display users dynamically -->
<!DOCTYPE html>
<html>
<body>
<h3>User List</h3>
<ul id="userList"></ul>
<script>
// Request data from PHP using Fetch API
fetch("fetch.php")
.then(response => response.json())
.then(data => {
let list = document.getElementById("userList");
data.forEach(user => {
let li = document.createElement("li");
li.textContent = user.name + " (" + user.email + ")";
list.appendChild(li);
});
})
.catch(error => console.error("Error:", error));
</script>
</body>
</html>
// fetch.php: Return MySQL data as JSON
<?php
header("Content-Type: application/json");
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$stmt = $pdo->query("SELECT name, email FROM users");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
The PHP script returns a JSON array of users. JavaScript loops through this array and dynamically creates list items, displaying names and emails instantly without reloading the page.
?️ Browser → ? Fetch Request → ? PHP Script → ?️ MySQL → ? JSON → ? DOM Update
created_at