Lesson 59 of 158 – PHP PUT API
59%

PHP PUT API

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.

Note: The PUT method is commonly used when the client wants to update an existing resource on the server.

1. What is the 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

2. PUT vs POST

Method Common Purpose
POST Create a new resource
PUT Update an existing resource

POST creates a new student, while PUT updates an existing student.

3. PUT API Endpoint

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.

4. Check the Request Method

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'PUT') {

    // Update student

}

5. Set JSON Response Header

Our API will receive and return JSON data.

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

This tells the client that the API response is JSON.

6. Include PDO Connection

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.

7. Receive PUT Data

PUT data is commonly sent in the request body as JSON.

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

This reads the raw request body.

8. Decode PUT JSON

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.

9. Example PUT Request

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

10. Read PUT Values

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

11. Validate Student ID

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

12. Validate Required Fields

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

13. Validate Email

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

14. UPDATE SQL Statement

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.

15. Prepare the UPDATE Query

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

The query uses placeholders instead of directly inserting user input.

16. Execute the UPDATE Query

Pass the values to the prepared statement.

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

The student matching the ID will be updated.

17. Check Affected Rows

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.

18. Student Not Found

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.

19. Successful Update Response

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

20. Complete Basic PUT API

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

?>

21. Add Try-Catch

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

22. Complete PUT API with Error Handling

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

}

?>

23. Test PUT API in Postman

Open Postman and select the PUT method.

PUT

http://localhost/rest_api/api/students.php

Go to Body → raw → JSON.

24. Send Update Data

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.

25. Successful PUT Response

If the student is updated successfully, the API can return:

200 OK

{
    "success": true,
    "message": "Student updated successfully"
}

26. Verify the Updated Record

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.

27. PUT API Flow

React Native / Postman
        ↓
PUT Request
        ↓
JSON Body
        ↓
json_decode()
        ↓
Validate Data
        ↓
PDO Prepared Statement
        ↓
UPDATE students
        ↓
MySQL
        ↓
JSON Response

28. PUT API and React Native

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

29. Important Security Practice

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.

30. PHP PUT API Summary

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

📌 Key Points

  • PUT is commonly used to update an existing resource.
  • PUT data can be sent in a JSON request body.
  • php://input reads the raw request body.
  • json_decode() converts JSON into PHP data.
  • The student ID identifies the record that should be updated.
  • UPDATE is used to modify an existing database record.
  • The WHERE clause is essential for selecting the correct record.
  • PDO prepared statements should be used for UPDATE queries.
  • HTTP 200 can indicate a successful update.
  • HTTP 400 can be used for invalid input.
  • HTTP 404 can be used when the requested student does not exist.
  • HTTP 500 can be used for database or server errors.
  • React Native can send PUT requests using Fetch or Axios.

🧠 Quick Quiz

Question: Which SQL statement is used to modify an existing record?