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.
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 |
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.
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.
| 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 |
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
);
The API should return JSON.
header("Content-Type: application/json");
This tells the client that the response body contains JSON data.
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.
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
]);
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
);
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.
POST is used to create a new student record.
$input = file_get_contents(
"php://input"
);
$data = json_decode(
$input,
true
);
$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;
}
$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.
$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.
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
]);
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;
}
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.
DELETE removes a student record from the database.
$id = $_GET['id'] ?? '';
$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;
}
If no record was deleted, the requested student may not exist.
http_response_code(200);
echo json_encode([
"success" => true,
"message" => "Student deleted successfully"
]);
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;
}
$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.
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.
REQUEST_METHOD
↓
┌────┼────┬──────┬────────┐
GET POST PUT DELETE
↓ ↓ ↓ ↓
Read Create Update Delete
↓ ↓ ↓ ↓
JSON
+
Status Code
$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"
);
}
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 |
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.
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"
}
]
}
<?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.
Question: Which HTTP method is commonly used to create a new resource in a CRUD REST API?