← Back to Chapters

PHP AJAX Delete Records From Database

?️ PHP AJAX Delete Records From Database

? Quick Overview

AJAX (Asynchronous JavaScript and XML) allows us to send requests to the server and receive data without refreshing the page. This tutorial demonstrates how to delete records from a MySQL database using AJAX and PHP for a smooth user experience.

? Key Concepts

  • Asynchronous server communication
  • AJAX request handling
  • PHP MySQL record deletion
  • Dynamic DOM manipulation

? How It Works

A list of records is loaded from the database. When a user clicks the delete button, an AJAX request is sent to PHP, the record is removed from the database, and the row is deleted from the page without refresh.

? Code Examples

HTML + JavaScript (AJAX)

? View Code Example
// Display table and handle AJAX delete
<table id="recordsTable">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</table>

<script>
function deleteRecord(id) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "delete.php?id=" + id, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var row = document.getElementById("row_" + id);
row.parentNode.removeChild(row);
}
};
xhr.send();
}

function loadRecords() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "fetch_records.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("recordsTable").innerHTML += xhr.responseText;
}
};
xhr.send();
}

window.onload = loadRecords;
</script>

fetch_records.php

? View Code Example
// Fetch records from database
<?php
$conn = new mysqli("localhost","username","password","database");
if ($conn->connect_error) {
die("Connection failed");
}

$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "<tr id='row_{$row['id']}'>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td><button onclick='deleteRecord({$row['id']})'>Delete</button></td>
</tr>";
}
$conn->close();
?>

delete.php

? View Code Example
// Delete record by ID
<?php
$conn = new mysqli("localhost","username","password","database");
if ($conn->connect_error) {
die("Connection failed");
}

if (isset($_GET['id'])) {
$id = $_GET['id'];
$conn->query("DELETE FROM users WHERE id=$id");
}
$conn->close();
?>

? Live Output / Explanation

When a record is deleted, the corresponding table row disappears instantly without refreshing the page.

? Use Cases

  • Admin dashboards
  • CRM systems
  • User management panels

✅ Tips & Best Practices

  • Use prepared statements for security
  • Validate and sanitize inputs
  • Show confirmation before deletion

? Try It Yourself

  • Add a confirmation dialog
  • Replace XMLHttpRequest with fetch()
  • Show success messages dynamically