PHP AJAX & MySQL
PHP AJAX & MySQL Tutorial
Combining PHP AJAX & MySQL allows you to dynamically fetch, insert, update, or delete database records without reloading the page. This is commonly used in live search, chat applications, dynamic tables, and dashboards.
1️⃣ How It Works
-
User triggers an event (e.g., clicking a button or typing in a search box).
-
AJAX (JavaScript) sends an asynchronous request to a PHP script.
-
PHP processes the request, interacts with MySQL database, and returns data (text, JSON, or HTML).
-
JavaScript receives the response and updates the web page dynamically.
2️⃣ Example: Fetch Data from MySQL using AJAX
Database Table users:
| id | name | |
|---|---|---|
| 1 | Vipul | vipul@example.com |
| 2 | Amit | amit@example.com |
| 3 | Ravi | ravi@example.com |
PHP Script (fetch_users.php):
HTML + JavaScript (index.html):
✅ Clicking the button loads data from MySQL via PHP without refreshing the page.
3️⃣ Example: Insert Data into MySQL via AJAX
HTML Form (index.html):
PHP Script (insert_user.php):
✅ This allows adding records to MySQL without page reload.
4️⃣ Key Points
-
AJAX communicates with PHP asynchronously; the page does not reload.
-
PHP handles server-side logic and interacts with MySQL database.
-
Data exchange is often done using JSON for structured data.
-
Use prepared statements for inserts/updates to prevent SQL injection.
-
Ideal for live search, dynamic tables, chat apps, dashboards, etc.
