Lesson 61 of 158 – PHP DELETE API
61%

PHP DELETE API

In the previous lessons, we learned how to retrieve, create, and update student records using REST API methods. Now we will learn how to delete an existing student record using the HTTP DELETE method.

Note: The DELETE method is commonly used when a client wants to remove an existing resource from the server.

1. What is the DELETE Method?

The HTTP DELETE method is commonly used to remove an existing resource.

In our Student Management API, DELETE can be used to remove a student from the database.

React Native
     ↓
DELETE Request
     ↓
PHP REST API
     ↓
MySQL
     ↓
Student Removed

2. DELETE vs Other HTTP Methods

Method Common Purpose
GET Retrieve data
POST Create data
PUT Update a resource
PATCH Partially update a resource
DELETE Remove a resource

3. DELETE API Endpoint

The student API endpoint can receive a DELETE request.

http://localhost/rest_api/api/students.php

The request must identify which student should be deleted.

4. Check the Request Method

PHP provides the HTTP request method using $_SERVER['REQUEST_METHOD'].

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'DELETE') {

    // Delete student

}

5. Set JSON Response Header

Our API returns JSON responses.

header("Content-Type: application/json");

This tells the client that the response is JSON.

6. Include PDO Connection

The API needs a database connection to delete the student.

require_once "../config/database.php";

The PDO connection is available through the $pdo variable.

7. Send Student ID

The API needs to know which student should be deleted.

One simple approach is to send the ID as a query parameter.

DELETE /api/students.php?id=5

Here, 5 is the student ID.

8. Read the ID from Query Parameter

PHP can read the ID using the $_GET array.

$id = $_GET['id'] ?? null;

The value should be validated before using it in a database query.

9. Validate the Student ID

The ID should be a positive integer.

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$id || $id <= 0) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Valid student ID is required"
    ]);

    exit;
}

10. DELETE SQL Statement

The SQL DELETE statement removes records from a table.

DELETE FROM students
WHERE id = ?

The WHERE condition is extremely important because it identifies the record that should be removed.

11. Why WHERE is Important

Never accidentally execute a DELETE query without a suitable WHERE condition when you intend to remove only one record.

DELETE FROM students
WHERE id = ?

The condition ensures that the API targets the requested student.

12. Prepare DELETE Query

Use a PDO prepared statement for the DELETE operation.

$stmt = $pdo->prepare(
    "DELETE FROM students WHERE id = ?"
);

The student ID is supplied separately from the SQL command.

13. Execute DELETE Query

Pass the student ID to the prepared statement.

$stmt->execute([$id]);

If the student exists, the matching record can be deleted.

14. Check Affected Rows

PDO's rowCount() can be used to check how many rows were affected by the DELETE operation.

$deleted = $stmt->rowCount();

For a delete-by-ID operation, a value of 1 normally means that one student was deleted.

15. Student Not Found

If no student matches the supplied ID, no row will be deleted.

if ($deleted === 0) {

    http_response_code(404);

    echo json_encode([
        "success" => false,
        "message" => "Student not found"
    ]);

    exit;
}

HTTP 404 indicates that the requested resource was not found.

16. Successful DELETE Response

After successfully deleting a student, the API can return a successful JSON response.

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" => "Student deleted successfully"
]);

17. DELETE Response Status

A successful DELETE request can return:

200 OK

Another commonly used successful response is:

204 No Content

When using 204, the server normally does not include a response body. For our beginner API, we will use 200 with a JSON message.

18. Complete Basic DELETE API

<?php

header("Content-Type: application/json");

require_once "../config/database.php";

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$id || $id <= 0) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Valid student ID is required"
    ]);

    exit;
}

$stmt = $pdo->prepare(
    "DELETE FROM students WHERE id = ?"
);

$stmt->execute([$id]);

if ($stmt->rowCount() === 0) {

    http_response_code(404);

    echo json_encode([
        "success" => false,
        "message" => "Student not found"
    ]);

    exit;
}

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" => "Student deleted successfully"
]);

?>

19. Handle Database Errors

Database errors should be handled using try-catch.

try {

    $stmt = $pdo->prepare(
        "DELETE FROM students WHERE id = ?"
    );

    $stmt->execute([$id]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" => "Database error"
    ]);

    exit;
}

20. Complete DELETE API with Error Handling

<?php

header("Content-Type: application/json");

require_once "../config/database.php";

$id = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$id || $id <= 0) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Valid student ID is required"
    ]);

    exit;
}

try {

    $stmt = $pdo->prepare(
        "DELETE FROM students WHERE id = ?"
    );

    $stmt->execute([$id]);

    if ($stmt->rowCount() === 0) {

        http_response_code(404);

        echo json_encode([
            "success" => false,
            "message" => "Student not found"
        ]);

        exit;
    }

    http_response_code(200);

    echo json_encode([
        "success" => true,
        "message" => "Student deleted successfully"
    ]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" => "Database error"
    ]);

}

?>

21. Test DELETE API in Postman

Open Postman and select the DELETE method.

DELETE

http://localhost/rest_api/api/students.php?id=5

Click Send to execute the request.

22. Successful Delete Response

If student ID 5 exists, the API can return:

200 OK

{
    "success": true,
    "message": "Student deleted successfully"
}

23. Test a Non-Existing Student

Try deleting an ID that does not exist.

DELETE

http://localhost/rest_api/api/students.php?id=999

The API should return:

404 Not Found

with a JSON message such as:

{
    "success": false,
    "message": "Student not found"
}

24. Test Missing ID

Try sending a DELETE request without an ID.

DELETE

http://localhost/rest_api/api/students.php

The API should return:

400 Bad Request

because the required student ID was not provided.

25. Verify the Deleted Student

After deleting a student, use the Get Single API with the same ID.

GET

http://localhost/rest_api/api/student.php?id=5

The API should now return:

404 Not Found

This confirms that the student record is no longer available.

26. Verify Using Get All API

You can also use the Get All API to check the remaining records.

GET

http://localhost/rest_api/api/students.php

The deleted student should no longer appear in the list.

27. DELETE API Flow

React Native / Postman
        ↓
DELETE Request
        ↓
Student ID
        ↓
Validate ID
        ↓
PDO Prepared Statement
        ↓
DELETE FROM students
        ↓
MySQL
        ↓
JSON Response

28. DELETE API with React Native

React Native can send a DELETE request when the user confirms that a student should be removed.

fetch(
    "http://localhost/rest_api/api/students.php?id=5",
    {
        method: "DELETE"
    }
)
.then(response => response.json())
.then(data => {
    console.log(data);
});

29. Important Security Practice

A DELETE API is a destructive operation. In a real application, it should normally be protected with authentication and authorization so that only permitted users can delete records.

Always validate the ID and use a prepared statement.

$stmt = $pdo->prepare(
    "DELETE FROM students WHERE id = ?"
);

$stmt->execute([$id]);

Do not directly concatenate a client-provided ID into the SQL query.

30. PHP DELETE API Summary

The DELETE API removes an existing student record using its ID. PHP validates the ID, executes a PDO prepared DELETE statement, checks whether a record was deleted, and returns a JSON response to the client.

DELETE
 ↓
Student ID
 ↓
Validate ID
 ↓
DELETE FROM students
 ↓
MySQL
 ↓
JSON Response

📌 Key Points

  • DELETE is commonly used to remove an existing resource.
  • The student ID identifies the record to delete.
  • PHP can read the ID from a query parameter.
  • The ID should be validated before the database operation.
  • DELETE FROM is used to remove a database record.
  • The WHERE clause is essential when deleting a specific record.
  • PDO prepared statements should be used for DELETE queries.
  • rowCount() can help determine whether a row was deleted.
  • HTTP 200 can be used for a successful JSON response.
  • HTTP 400 can be used for invalid input.
  • HTTP 404 can indicate that the requested student was not found.
  • HTTP 500 can indicate a database or server error.
  • DELETE APIs should normally require proper authentication and authorization in real applications.
  • React Native can send DELETE requests using Fetch or Axios.

🧠 Quick Quiz

Question: Which SQL statement is used to remove a record from a database table?