← Back to Chapters

PHP REST API – Delete & Search Data

? PHP REST API – Delete & Search Data

? Quick Overview

This topic explains how to build REST API endpoints in PHP to delete records using DELETE requests and search data using GET queries with JSON responses.

? Key Concepts

  • DELETE method for removing records
  • GET method for searching data
  • JSON-based API communication
  • MySQL database interaction

?️ Delete API (DELETE)

? View Code Example
// delete.php – deletes a user by ID using DELETE request
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: DELETE");

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

$conn = new mysqli("localhost", "root", "", "rest_api");

if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed"]));
}

$sql = "DELETE FROM users WHERE id=$id";
if ($conn->query($sql)) {
    echo json_encode(["message" => "User deleted successfully"]);
} else {
    echo json_encode(["error" => "Failed to delete user"]);
}

$conn->close();
?>

? Search API (GET)

? View Code Example
// search.php – searches users by name or email
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: GET");

$conn = new mysqli("localhost", "root", "", "rest_api");

if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed"]));
}

$keyword = $_GET['q'] ?? '';

$sql = "SELECT * FROM users WHERE name LIKE '%$keyword%' OR email LIKE '%$keyword%'";
$result = $conn->query($sql);

$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

echo json_encode($data);
$conn->close();
?>

? Example JSON Requests

? View Code Example
// Sample DELETE and SEARCH requests with JSON response
// DELETE /delete.php
{
  "id": 3
}

// GET /search.php?q=alice
[
  {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com"
  }
]

? Use Cases

  • Deleting users or records from admin dashboards
  • Searching users in CRM or management systems
  • Building RESTful APIs for frontend apps

✅ Tips & Best Practices

  • Use prepared statements to avoid SQL injection
  • Return proper HTTP status codes
  • Limit search results for performance

? Try It Yourself

  • Add bulk delete support using array IDs
  • Implement pagination in search results
  • Consume the API using Fetch or Postman