Lesson 144 of 158 – Project Update Student API
91%

Project Update Student API

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.

Project Goal: Update an existing student securely using the HTTP PUT method, JWT authentication, PHP, MySQL, PDO, Axios, and TypeScript.

1. Update Student API Flow

React Native Edit Screen
        ↓
     Axios PUT
        ↓
students.php?id=5
        ↓
JWT Verification
        ↓
Validate Student ID
        ↓
Validate Request Data
        ↓
PDO UPDATE
        ↓
MySQL
        ↓
JSON Response

2. HTTP PUT Method

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.

3. Update Request Body

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "mobile": "9876543211",
    "course": "React Native",
    "address": "Patna"
}

The request contains the new values for the student.

4. API Content Type

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

The API returns JSON and expects JSON data from the mobile application.

5. Database Connection

require_once '../config/database.php';

The existing PDO connection is used to update the student record.

6. JWT Authentication

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.

7. Read Authorization Header

$headers = getallheaders();

$authorization =
    $headers['Authorization']
    ?? '';

The Authorization header contains the Bearer token.

8. Extract 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];

9. Verify JWT

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;
}

10. Check HTTP Method

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.

11. Get Student ID

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

12. Validate Student ID

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

    http_response_code(400);

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

    exit;
}

13. Check Student Exists

$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;
}

14. Read JSON Request

$input = json_decode(
    file_get_contents("php://input"),
    true
);

The JSON request body is converted into a PHP associative array.

15. Get Updated Student Data

$name =
    trim($input['name'] ?? '');

$email =
    trim($input['email'] ?? '');

$mobile =
    trim($input['mobile'] ?? '');

$course =
    trim($input['course'] ?? '');

$address =
    trim($input['address'] ?? '');

16. Validate Name

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.

17. Validate Email

if (
    $email !== '' &&
    !filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    )
) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid email address"
    ]);

    exit;
}

18. Validate Mobile

if (
    $mobile !== '' &&
    !preg_match(
        '/^[0-9]{10,15}$/',
        $mobile
    )
) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid mobile number"
    ]);

    exit;
}

19. Validate Course

if ($course === '') {

    http_response_code(422);

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

    exit;
}

20. Update Student in MySQL

$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.

21. Check Update Result

$updated =
    $stmt->rowCount();

rowCount() can be used to inspect the number of rows affected by the UPDATE statement.

Note: If the submitted values are identical to the existing values, some MySQL configurations may report zero affected rows even though the student record exists.

22. Successful Update Response

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.

23. Complete PHP Update API

<?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"
    ]);
}

24. React Native Edit Screen

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

25. TypeScript Update Request

interface UpdateStudentRequest {
    name: string;
    email: string;
    mobile: string;
    course: string;
    address: string;
}

This interface defines the data sent to the update API.

26. Axios PUT Request

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.

27. Handle Update Success

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.

28. Testing with Postman

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"
}

29. Update Student Flow

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

30. Update Student API Summary

The Update Student API allows authenticated users to modify an existing student record.

  • PUT is used for the update operation.
  • The student ID is supplied as a query parameter.
  • A valid JWT is required.
  • The API verifies that the student exists.
  • The request body contains the updated information.
  • Server-side validation is performed.
  • PDO prepared statements are used for UPDATE.
  • HTTP 200 indicates a successful update.
  • Axios sends the PUT request from React Native.
  • The next lesson will implement student deletion.

📌 Key Points

  • The Update Student API uses PUT.
  • The student ID is passed using ?id=.
  • A valid JWT should be required.
  • The API should verify that the student exists.
  • Updated data should be validated on the server.
  • PDO prepared statements should be used for UPDATE.
  • rowCount() can be used to inspect affected rows.
  • HTTP 404 is used when the student does not exist.
  • HTTP 422 can be used for validation errors.
  • Axios can send the update request from React Native.

🧠 Quick Quiz

Question: Which HTTP method is used in this project to update an existing student?