← Back to Chapters

PHP MySQL Read Data with JS Fetch Method

? PHP MySQL Read Data with JS Fetch Method

? Quick Overview

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.

? Key Concepts

  • Asynchronous data fetching using Fetch API
  • PHP as a backend API returning JSON
  • MySQL database interaction via PDO
  • Dynamic DOM updates with JavaScript

? Syntax & Theory

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.

? Code Example

? View Code Example
<!-- 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);
?>

? Live Output / Explanation

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.

? Interactive Flow

?️ Browser → ? Fetch Request → ? PHP Script → ?️ MySQL → ? JSON → ? DOM Update

? Use Cases

  • Displaying user lists or dashboards
  • Loading data without page refresh
  • Building REST-style PHP APIs
  • Search, filters, and pagination

✅ Tips & Best Practices

  • Always return valid JSON from PHP
  • Use prepared statements for security
  • Handle network and parsing errors properly
  • Use browser DevTools for debugging

? Try It Yourself

  • Fetch additional columns like created_at
  • Add a search input to filter users
  • Limit results and add pagination