In this lesson, we will create the Update Student API for our Student Management mobile application.
The React Native application will send the updated student information using Axios. The PHP REST API will verify the JWT, validate the data, check whether the student exists, and update the record in MySQL using PDO.
React Native Edit Screen
↓
Axios PUT
↓
students.php?id=5
↓
JWT Verification
↓
Validate Student ID
↓
Validate Request Data
↓
PDO UPDATE
↓
MySQL
↓
JSON Response
The PUT method is commonly used when replacing or updating an existing resource.
PUT /api/students.php?id=5
The student ID identifies which record should be updated.
{
"name": "Rahul Kumar",
"email": "rahul@example.com",
"mobile": "9876543211",
"course": "React Native",
"address": "Patna"
}
The request contains the new values for the student.
header(
"Content-Type: application/json"
);
The API returns JSON and expects JSON data from the mobile application.
require_once '../config/database.php';
The existing PDO connection is used to update the student record.
Updating a student is a protected operation. The mobile application must send a valid JWT.
Authorization:
Bearer YOUR_JWT_TOKEN
The server should verify the token before performing the update.
$headers = getallheaders();
$authorization =
$headers['Authorization']
?? '';
The Authorization header contains the Bearer token.
if (
!preg_match(
'/Bearer\s(\S+)/',
$authorization,
$matches
)
) {
http_response_code(401);
echo json_encode([
"success" => false,
"message" =>
"Authentication required"
]);
exit;
}
$token = $matches[1];
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
try {
$decoded = JWT::decode(
$token,
new Key(
$secretKey,
'HS256'
)
);
} catch (Exception $e) {
http_response_code(401);
echo json_encode([
"success" => false,
"message" =>
"Invalid or expired token"
]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
http_response_code(405);
echo json_encode([
"success" => false,
"message" => "Method not allowed"
]);
exit;
}
Only PUT requests should be processed by this update endpoint.
The student ID is passed through the query string.
$id = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
Example:
PUT /api/students.php?id=5
if (!$id || $id <= 0) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" =>
"Valid student ID is required"
]);
exit;
}
$stmt = $pdo->prepare(
"SELECT id
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;
}
$input = json_decode(
file_get_contents("php://input"),
true
);
The JSON request body is converted into a PHP associative array.
$name =
trim($input['name'] ?? '');
$email =
trim($input['email'] ?? '');
$mobile =
trim($input['mobile'] ?? '');
$course =
trim($input['course'] ?? '');
$address =
trim($input['address'] ?? '');
if ($name === '') {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Student name is required"
]);
exit;
}
Validation should be performed on the server even if the mobile form already performs validation.
if (
$email !== '' &&
!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Invalid email address"
]);
exit;
}
if (
$mobile !== '' &&
!preg_match(
'/^[0-9]{10,15}$/',
$mobile
)
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Invalid mobile number"
]);
exit;
}
if ($course === '') {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Course is required"
]);
exit;
}
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?,
address = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$mobile,
$course,
$address,
$id
]);
Prepared statements safely pass the values to MySQL.
$updated =
$stmt->rowCount();
rowCount() can be used to inspect the number of rows
affected by the UPDATE statement.
http_response_code(200);
echo json_encode([
"success" => true,
"message" =>
"Student updated successfully"
]);
HTTP 200 is appropriate for a successful update that returns a response body.
<?php
header(
"Content-Type: application/json"
);
require_once '../config/database.php';
require_once __DIR__ .
'/vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$secretKey =
'CHANGE_THIS_TO_A_LONG_RANDOM_SECRET';
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
http_response_code(405);
echo json_encode([
"success" => false,
"message" => "Method not allowed"
]);
exit;
}
$headers = getallheaders();
$authorization =
$headers['Authorization']
?? '';
if (
!preg_match(
'/Bearer\s(\S+)/',
$authorization,
$matches
)
) {
http_response_code(401);
echo json_encode([
"success" => false,
"message" =>
"Authentication required"
]);
exit;
}
$token = $matches[1];
try {
$decoded = JWT::decode(
$token,
new Key(
$secretKey,
'HS256'
)
);
$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(
"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;
}
$input = json_decode(
file_get_contents("php://input"),
true
);
$name =
trim($input['name'] ?? '');
$email =
trim($input['email'] ?? '');
$mobile =
trim($input['mobile'] ?? '');
$course =
trim($input['course'] ?? '');
$address =
trim($input['address'] ?? '');
if ($name === '') {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Student name is required"
]);
exit;
}
if (
$email !== '' &&
!filter_var(
$email,
FILTER_VALIDATE_EMAIL
)
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Invalid email address"
]);
exit;
}
if (
$mobile !== '' &&
!preg_match(
'/^[0-9]{10,15}$/',
$mobile
)
) {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Invalid mobile number"
]);
exit;
}
if ($course === '') {
http_response_code(422);
echo json_encode([
"success" => false,
"message" =>
"Course is required"
]);
exit;
}
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?,
email = ?,
mobile = ?,
course = ?,
address = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$mobile,
$course,
$address,
$id
]);
http_response_code(200);
echo json_encode([
"success" => true,
"message" =>
"Student updated successfully"
]);
} catch (Exception $e) {
error_log($e->getMessage());
http_response_code(401);
echo json_encode([
"success" => false,
"message" =>
"Invalid or expired token"
]);
}
The Edit Student screen can load the existing student information into form fields.
Student Details
↓
Edit Button
↓
Edit Student Screen
↓
Load Existing Values
↓
Modify Values
↓
Update Button
interface UpdateStudentRequest {
name: string;
email: string;
mobile: string;
course: string;
address: string;
}
This interface defines the data sent to the update API.
const response =
await api.put(
`/students.php?id=${studentId}`,
{
name,
email,
mobile,
course,
address
}
);
The student ID is included in the URL while the updated information is sent in the JSON request body.
if (response.data.success) {
Alert.alert(
"Success",
response.data.message
);
// Navigate back
// Refresh student list
}
After updating the student, the application can return to the Student List screen and reload the data.
Method: PUT
URL:
https://example.com/api/students.php?id=5
Headers:
Content-Type: application/json
Authorization: Bearer YOUR_JWT_TOKEN
Body:
{
"name": "Rahul Kumar Updated",
"email": "rahul@example.com",
"mobile": "9876543211",
"course": "React Native",
"address": "Patna"
}
Edit Student Screen
↓
TypeScript Form
↓
Axios PUT
↓
JWT Authorization
↓
PHP students.php
↓
Verify JWT
↓
Validate Student ID
↓
Validate Form Data
↓
PDO UPDATE
↓
MySQL
↓
HTTP 200
↓
React Native
↓
Refresh Student List
The Update Student API allows authenticated users to modify an existing student record.
?id=.rowCount() can be used to inspect affected rows.Question: Which HTTP method is used in this project to update an existing student?