AJAX and MySQL with PHP – Dynamic Database Operations Tutorial

AJAX and MySQL – PHP Complete Beginner Tutorial

Combining AJAX, PHP, and MySQL allows you to build fast, interactive, and dynamic web applications. Data can be fetched or updated from the database without reloading the page, providing a smooth user experience.

This tutorial explains how AJAX works with PHP and MySQL, using clear examples and real outputs.


What Does AJAX and MySQL Mean in PHP?

AJAX is used on the client side to send requests, while PHP handles server-side logic and MySQL manages database storage.

Flow:

  1. User triggers an action
  2. AJAX sends request to PHP
  3. PHP queries MySQL
  4. MySQL returns data
  5. PHP sends response
  6. AJAX updates the page

Why Use AJAX with MySQL in PHP?

Using AJAX with MySQL helps to:

  • Load data instantly
  • Update content without refresh
  • Create live search systems
  • Build dynamic dashboards
  • Reduce server load

Prerequisites for AJAX MySQL Tutorial

Before proceeding, ensure you know:

  • Basic HTML and JavaScript
  • PHP fundamentals
  • MySQL basics
  • Database connection concepts

Sample MySQL Table Used in Examples

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);

PHP MySQL Database Connection File

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");

if (!$conn) {
    die("Database connection failed");
}
?>

Example 1: Fetch Data from MySQL Using AJAX and PHP

This example shows how to load database data without page reload.


Step 1: HTML and JavaScript (index.html)

<!DOCTYPE html>
<html>
<head>
    <title>AJAX MySQL Example</title>
    <script>
        function loadUsers() {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "fetch.php", true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }
    </script>
</head>
<body>

<button onclick="loadUsers()">Load Users</button>
<div id="result"></div>

</body>
</html>

Step 2: PHP File to Fetch MySQL Data (fetch.php)

<?php
include "db.php";

$result = mysqli_query($conn, "SELECT * FROM users");

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . " - " . $row['email'] . "<br>";
}
?>

Output on Button Click

Rahul - rahul@gmail.com
Amit - amit@gmail.com
Neha - neha@gmail.com

Example 2: Send Data to MySQL Using AJAX and PHP

This example inserts data into MySQL without refreshing the page.


Step 1: HTML Form

<form onsubmit="saveData(); return false;">
    <input type="text" id="name" placeholder="Enter Name">
    <input type="email" id="email" placeholder="Enter Email">
    <button type="submit">Save</button>
</form>

<div id="msg"></div>

Step 2: JavaScript AJAX POST Request

<script>
function saveData() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "insert.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("msg").innerHTML = xhr.responseText;
        }
    };

    xhr.send("name=" + name + "&email=" + email);
}
</script>

Step 3: PHP Insert Script (insert.php)

<?php
include "db.php";

$name = $_POST['name'];
$email = $_POST['email'];

mysqli_query($conn,
    "INSERT INTO users (name, email)
     VALUES ('$name', '$email')");

echo "Data inserted successfully";
?>

Output

Data inserted successfully

Example 3: Live Search Using AJAX and MySQL

AJAX is commonly used for real-time search.

SELECT * FROM users WHERE name LIKE '%keyword%';

This integrates with the PHP MySQL Search Using LIKE tutorial.


Common Errors When Using AJAX with MySQL

  • Database connection failure
  • Incorrect AJAX URL
  • SQL syntax errors
  • Not handling response properly

AJAX and MySQL PHP, PHP AJAX MySQL tutorial, PHP AJAX database example, AJAX fetch data MySQL PHP, PHP asynchronous database operations


Best Practices for AJAX MySQL with PHP

  • Always validate data in PHP
  • Use prepared statements
  • Return JSON for structured data
  • Handle AJAX errors gracefully
  • Avoid exposing sensitive data

Related tutorial:


Frequently Asked Questions (FAQ)

1. Can AJAX work with MySQL directly?

No, AJAX communicates with PHP, not MySQL.

2. Does AJAX require PHP?

No, but PHP is commonly used.

3. Can AJAX update database records?

Yes, via PHP scripts.

4. Is AJAX secure?

Yes, if PHP validation is applied.

5. Is AJAX still relevant?

Yes, widely used in modern web apps.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more