← Back to Chapters

PHP MySQL Delete Data with JS Fetch

?️ PHP MySQL Delete Data with JS Fetch

? Quick Overview

This topic explains how to delete records from a MySQL database using PHP while triggering the request from JavaScript using the Fetch API.

? Key Concepts

  • JavaScript Fetch API
  • AJAX-based deletion
  • PHP backend handling
  • MySQL DELETE query

? Syntax & Theory

The fetch() method sends asynchronous HTTP requests. When deleting data, it usually uses POST or DELETE methods and sends JSON data to a PHP script.

? Code Examples

? View Code Example
// JavaScript function sending delete request using Fetch API
function deleteUser(id) {
fetch("delete.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: id })
})
.then(response => response.text())
.then(data => console.log(data));
}

// Example usage
deleteUser(2);
? View PHP Backend Code
// PHP script to receive JSON data and delete a record
$conn = new mysqli("localhost","root","","testdb");

$data = json_decode(file_get_contents("php://input"), true);
$id = $data['id'];

$sql = "DELETE FROM users WHERE id=$id";

if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record";
}

$conn->close();

? Live Output / Explanation

When the delete function runs, a network request is sent to delete.php. If successful, the server responds with a confirmation message.

? Interactive Concept

Imagine a table with a delete button beside each user. Clicking the button triggers the JavaScript function, removing the record without reloading the page.

? Use Cases

  • Admin dashboards
  • User management panels
  • Dynamic CRUD applications

? Tips & Best Practices

  • Always use prepared statements for security
  • Confirm deletion before executing
  • Monitor network requests using browser dev tools

? Try It Yourself

Create a dynamic user list with delete buttons and remove users instantly using Fetch API.