Lesson 65 of 158 – PHP CRUD API
65%

PHP CRUD API

CRUD stands for Create, Read, Update, and Delete. These four operations are the foundation of most database applications. In this lesson, we will combine the PHP REST API concepts learned so far to create a complete CRUD API for student records.

Note: This lesson combines GET, POST, PUT, PATCH, DELETE, JSON, PDO, validation, HTTP status codes, and error handling into one practical REST API structure.

1. What is CRUD?

CRUD represents the four basic database operations:

Operation HTTP Method Purpose
Create POST Add a new record
Read GET Retrieve records
Update PUT / PATCH Modify records
Delete DELETE Remove records

2. CRUD API Architecture

React Native Mobile App
          ↓
      HTTP Request
          ↓
       PHP API
          ↓
        PDO
          ↓
       MySQL
          ↓
        PDO
          ↓
       PHP API
          ↓
      JSON Response
          ↓
React Native Mobile App

The mobile application communicates with the PHP API instead of directly connecting to the MySQL database.

3. Student CRUD Example

For this lesson, we will use a student resource.

students

id
name
email
mobile
course

The API will allow the mobile application to create, view, update, and delete student records.

4. CRUD API Endpoints

Method Endpoint Operation
GET /students Get all students
GET /students?id=1 Get one student
POST /students Create student
PUT /students Update student
DELETE /students?id=1 Delete student

5. Create Database Connection

A PDO connection can be used to communicate with MySQL.

$pdo = new PDO(
    "mysql:host=localhost;dbname=schooldb",
    "root",
    ""
);

$pdo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

6. Set JSON Header

The API should return JSON.

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

This tells the client that the response body contains JSON data.

7. Read the HTTP Method

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

$method = $_SERVER['REQUEST_METHOD'];

echo $method;

The result can be GET, POST, PUT, PATCH, or DELETE.

8. GET – Read All Students

A GET request can retrieve all student records.

$stmt = $pdo->prepare(
    "SELECT * FROM students ORDER BY id DESC"
);

$stmt->execute();

$students = $stmt->fetchAll(
    PDO::FETCH_ASSOC
);

http_response_code(200);

echo json_encode([
    "success" => true,
    "data" => $students
]);

9. GET – Read One Student

A student can be retrieved using an ID.

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

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

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

$student = $stmt->fetch(
    PDO::FETCH_ASSOC
);

10. Check Student Exists

if (!$student) {

    http_response_code(404);

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

    exit;
}

HTTP 404 is appropriate when the requested student does not exist.

11. POST – Create Student

POST is used to create a new student record.

$input = file_get_contents(
    "php://input"
);

$data = json_decode(
    $input,
    true
);

12. Validate POST Data

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');

if (
    $name === '' ||
    $email === '' ||
    $mobile === '' ||
    $course === ''
) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "All fields are required"
    ]);

    exit;
}

13. Insert Student

$stmt = $pdo->prepare(
    "INSERT INTO students
    (name, email, mobile, course)
    VALUES (?, ?, ?, ?)"
);

$stmt->execute([
    $name,
    $email,
    $mobile,
    $course
]);

Prepared statements help protect the database from SQL injection.

14. Return Created Student ID

$id = $pdo->lastInsertId();

http_response_code(201);

echo json_encode([
    "success" => true,
    "message" => "Student created successfully",
    "student_id" => $id
]);

HTTP 201 indicates that a new resource was created.

15. PUT – Update Student

PUT can be used to update the student's complete set of editable fields.

$id = $data['id'] ?? 0;

$stmt = $pdo->prepare(
    "UPDATE students
     SET name = ?,
         email = ?,
         mobile = ?,
         course = ?
     WHERE id = ?"
);

$stmt->execute([
    $name,
    $email,
    $mobile,
    $course,
    $id
]);

16. Check PUT Result

After an update, the API should check whether the requested student exists.

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

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

if (!$stmt->fetch()) {

    http_response_code(404);

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

    exit;
}

17. PATCH – Partial Update

PATCH is useful when only some student fields need to be updated.

PATCH /students

{
    "id": 5,
    "mobile": "9876543210"
}

Only the mobile number needs to be changed in this example.

18. DELETE – Remove Student

DELETE removes a student record from the database.

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

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

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

19. Check DELETE Result

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

    http_response_code(404);

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

    exit;
}

If no record was deleted, the requested student may not exist.

20. Successful DELETE Response

http_response_code(200);

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

21. Create an Error Function

A reusable function can simplify error responses throughout the CRUD API.

function sendError(
    int $status,
    string $message
) {

    http_response_code($status);

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

    exit;
}

22. Validate Student ID

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

if (!filter_var(
    $id,
    FILTER_VALIDATE_INT
)) {

    sendError(
        400,
        "Invalid student ID"
    );
}

Always validate an ID before using it in database operations.

23. Handle Database Exceptions

try {

    $stmt = $pdo->prepare(
        "SELECT * FROM students"
    );

    $stmt->execute();

} catch (PDOException $e) {

    error_log(
        $e->getMessage()
    );

    sendError(
        500,
        "Database operation failed"
    );
}

The technical database error is logged on the server instead of being exposed to the mobile application.

24. CRUD API Method Flow

REQUEST_METHOD
      ↓
 ┌────┼────┬──────┬────────┐
GET  POST  PUT   DELETE
 ↓    ↓     ↓       ↓
Read Create Update Delete
 ↓    ↓     ↓       ↓
          JSON
          +
      Status Code

25. Complete Method Switch

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {

    case 'GET':
        // Read
        break;

    case 'POST':
        // Create
        break;

    case 'PUT':
        // Update
        break;

    case 'PATCH':
        // Partial Update
        break;

    case 'DELETE':
        // Delete
        break;

    default:

        sendError(
            405,
            "Method not allowed"
        );
}

26. Test CRUD API with Postman

Postman can be used to test every CRUD operation.

Test Method
Get all students GET
Get one student GET
Create student POST
Update student PUT
Delete student DELETE

27. React Native CRUD Flow

React Native Screen
        ↓
Fetch / Axios
        ↓
PHP CRUD API
        ↓
MySQL Database
        ↓
JSON Response
        ↓
Update React Native UI

This is the basic architecture used by many mobile applications.

28. CRUD API Response Example

A successful API response can contain a consistent structure.

{
    "success": true,
    "message": "Students fetched successfully",
    "data": [
        {
            "id": 1,
            "name": "Rahul",
            "email": "rahul@example.com",
            "mobile": "9876543210",
            "course": "React Native"
        }
    ]
}

29. CRUD API Best Practices

  • Use the correct HTTP method for each operation.
  • Use prepared statements for database queries.
  • Validate all incoming data.
  • Return JSON responses consistently.
  • Use appropriate HTTP status codes.
  • Handle database exceptions.
  • Do not expose sensitive information.
  • Use authentication for protected resources.
  • Keep API endpoints organized.
  • Test APIs with Postman before integrating them into React Native.

30. Complete CRUD API Structure

<?php

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

function sendError(
    int $status,
    string $message
) {

    http_response_code($status);

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

    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

try {

    switch ($method) {

        case 'GET':

            // SELECT students

            break;

        case 'POST':

            // INSERT student

            break;

        case 'PUT':

            // UPDATE student

            break;

        case 'PATCH':

            // PARTIAL UPDATE

            break;

        case 'DELETE':

            // DELETE student

            break;

        default:

            sendError(
                405,
                "Method not allowed"
            );
    }

} catch (PDOException $e) {

    error_log(
        $e->getMessage()
    );

    sendError(
        500,
        "Database operation failed"
    );
}

?>

This structure provides a starting point for a complete PHP CRUD REST API. The individual operations can be implemented inside their respective method blocks.

📌 Key Points

  • CRUD means Create, Read, Update, and Delete.
  • POST is commonly used to create resources.
  • GET is used to retrieve resources.
  • PUT is commonly used for complete updates.
  • PATCH is useful for partial updates.
  • DELETE is used to remove resources.
  • PDO can connect PHP REST APIs to MySQL.
  • Prepared statements help protect database queries.
  • Input should always be validated.
  • API responses should use JSON.
  • HTTP status codes communicate the result of an operation.
  • 404 can be used when a requested resource does not exist.
  • 405 can be used when an HTTP method is not supported.
  • 500 can be used for unexpected server-side errors.
  • Database exceptions should be handled safely.
  • Technical errors should be logged instead of exposed to clients.
  • Postman can be used to test CRUD endpoints.
  • React Native can consume the CRUD API using Fetch or Axios.
  • CRUD APIs form the foundation of many mobile application backends.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to create a new resource in a CRUD REST API?