In the previous lessons, we learned how to create and retrieve student records using GET and POST APIs. Now we will learn how to update an existing student record using the HTTP PUT method.
The HTTP PUT method is commonly used to update an existing resource.
In our Student Management API, PUT can be used to update a student's information.
React Native
↓
PUT Request
↓
PHP REST API
↓
MySQL
↓
Updated Student
| Method | Common Purpose |
|---|---|
| POST | Create a new resource |
| PUT | Update an existing resource |
POST creates a new student, while PUT updates an existing student.
The student endpoint can receive a PUT request.
http://localhost/rest_api/api/students.php
The request body will contain the student ID and the values that should be updated.
PHP provides the current HTTP method through $_SERVER['REQUEST_METHOD'].
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'PUT') {
// Update student
}
Our API will receive and return JSON data.
header("Content-Type: application/json");
This tells the client that the API response is JSON.
The API needs the PDO connection to communicate with MySQL.
require_once "../config/database.php";
After including the file, the API can use the $pdo object.
PUT data is commonly sent in the request body as JSON.
$input = file_get_contents("php://input");
This reads the raw request body.
Convert the JSON request body into a PHP associative array.
$data = json_decode(
file_get_contents("php://input"),
true
);
The second argument true returns an associative array.
A client can send the following JSON to update student ID 1:
{
"id": 1,
"name": "Rahul Kumar",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "React Native"
}
$id = $data['id'] ?? 0;
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');
These values will be used to update the selected student.
The student ID is required because the API needs to know which record should be updated.
$id = filter_var(
$data['id'] ?? null,
FILTER_VALIDATE_INT
);
if (!$id || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Valid student ID is required"
]);
exit;
}
Required fields should be checked before updating the database.
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
Use filter_var() to validate the email format.
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email address"
]);
exit;
}
The SQL UPDATE statement is used to modify an existing database record.
UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?
WHERE id = ?
The WHERE condition is important because it identifies the record to update.
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?
WHERE id = ?"
);
The query uses placeholders instead of directly inserting user input.
Pass the values to the prepared statement.
$stmt->execute([
$name,
$email,
$mobile,
$course,
$id
]);
The student matching the ID will be updated.
PDO provides rowCount() to check how many rows were affected by the UPDATE operation.
$updated = $stmt->rowCount();
This can help determine whether a matching record was changed.
If no record matches the supplied ID, the API should return an appropriate response.
if ($updated === 0) {
http_response_code(404);
echo json_encode([
"success" => false,
"message" => "Student not found"
]);
exit;
}
For production APIs, remember that rowCount() can also be zero when the record exists but the submitted values are identical. A separate existence check can distinguish those cases.
After a successful update, the API can return HTTP status code 200 OK.
http_response_code(200);
echo json_encode([
"success" => true,
"message" => "Student updated successfully"
]);
<?php
header("Content-Type: application/json");
require_once "../config/database.php";
$data = json_decode(
file_get_contents("php://input"),
true
);
$id = filter_var(
$data['id'] ?? null,
FILTER_VALIDATE_INT
);
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');
if (!$id || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Valid student ID is required"
]);
exit;
}
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email address"
]);
exit;
}
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$mobile,
$course,
$id
]);
http_response_code(200);
echo json_encode([
"success" => true,
"message" => "Student updated successfully"
]);
?>
Database operations should be handled with try-catch so that database errors can be returned as proper API responses.
try {
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$mobile,
$course,
$id
]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Database error"
]);
exit;
}
<?php
header("Content-Type: application/json");
require_once "../config/database.php";
$data = json_decode(
file_get_contents("php://input"),
true
);
if (!is_array($data)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid JSON data"
]);
exit;
}
$id = filter_var(
$data['id'] ?? null,
FILTER_VALIDATE_INT
);
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');
if (!$id || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Valid student ID is required"
]);
exit;
}
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
if (!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid email address"
]);
exit;
}
try {
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$mobile,
$course,
$id
]);
http_response_code(200);
echo json_encode([
"success" => true,
"message" => "Student updated successfully"
]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Database error"
]);
}
?>
Open Postman and select the PUT method.
PUT
http://localhost/rest_api/api/students.php
Go to Body → raw → JSON.
Send the student ID along with the updated values.
{
"id": 1,
"name": "Rahul Kumar",
"email": "rahulkumar@example.com",
"mobile": "9876543210",
"course": "React Native"
}
Then click Send.
If the student is updated successfully, the API can return:
200 OK{ "success": true, "message": "Student updated successfully" }
After updating the student, use the Get Single API to verify the new data.
GET
http://localhost/rest_api/api/student.php?id=1
The response should contain the updated student information.
React Native / Postman
↓
PUT Request
↓
JSON Body
↓
json_decode()
↓
Validate Data
↓
PDO Prepared Statement
↓
UPDATE students
↓
MySQL
↓
JSON Response
React Native can send a PUT request when the user edits a student profile.
fetch("http://localhost/rest_api/api/students.php", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
id: 1,
name: "Rahul Kumar",
email: "rahulkumar@example.com",
mobile: "9876543210",
course: "React Native"
})
});
Always validate the received data and use prepared statements for UPDATE queries.
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$mobile,
$course,
$id
]);
Never directly concatenate client-provided values into SQL queries.
The PUT API receives an existing student's ID and updated information in JSON format. PHP validates the data, uses a PDO prepared statement to execute an UPDATE query, and returns a JSON response indicating whether the operation was successful.
PUT
↓
JSON Body
↓
Validate ID & Data
↓
UPDATE students
↓
MySQL
↓
JSON Response
Question: Which SQL statement is used to modify an existing record?