Ajax Database in PHP
Nice! Let’s go over how to use AJAX with PHP to interact with a database — this is super useful for creating dynamic web apps that update without reloading the page.
? What You'll Learn
How to use AJAX (via jQuery or plain JS)
How to connect to a database using PHP
How to send and receive data without page reloads
? Simple Example: Fetch Data from MySQL with AJAX + PHP
? 1. Database Setup (MySQL)
Suppose you have a table users:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100));? 2. PHP File (get_users.php)
<?php$connect = new mysqli("localhost", "root", "", "test_db");if ($connect->connect_error) { die("Connection failed: " . $connect->connect_error);}$result = $connect->query("SELECT * FROM users");$users = [];while ($row = $result->fetch_assoc()) { $users[] = $row;}echo json_encode($users);?>? 3. HTML + AJAX (index.html)
<!DOCTYPE html><html><head> <title>AJAX PHP MySQL</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><h2>User List</h2><ul id="userList"></ul><script>$(document).ready(function(){ $.ajax({ url: "get_users.php", type: "GET", dataType: "json", success: function(data){ $.each(data, function(index, user){ $("#userList").append("<li>" + user.name + " (" + user.email + ")</li>"); }); } });});</script></body></html>? What's Happening
HTML page loads and runs jQuery.
jQuery sends an AJAX
GETrequest toget_users.php.PHP connects to MySQL, fetches data, and returns it as JSON.
JavaScript receives the JSON and updates the page without reloading.
?? Want to Try More?
Insert data with AJAX
Use dropdowns (like dynamic dependent dropdowns)
Live search/filter with AJAX
Pagination with AJAX