← Back to Chapters

PHP REST API – Create & Update Data

? PHP REST API – Create & Update Data

⚡ Quick Overview

This topic explains how to build a simple PHP REST API that can create new records and update existing records using JSON-based HTTP requests.

? Key Concepts

  • RESTful API principles
  • HTTP methods: POST and PUT
  • JSON request and response handling
  • Database interaction using MySQL

? Syntax & Theory

The API accepts JSON input via php://input and processes it on the server. Data is exchanged in JSON format and responses are also returned as JSON.

? Create (POST) Example

? View Code Example
// Create a new user using POST request
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");

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

$name = $data['name'] ?? '';
$email = $data['email'] ?? '';

$conn = new mysqli("localhost", "root", "", "rest_api");

if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed"]));
}

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql)) {
    echo json_encode(["message" => "User created successfully"]);
} else {
    echo json_encode(["error" => "Failed to create user"]);
}
$conn->close();
?>

✏️ Update (PUT) Example

? View Code Example
// Update an existing user using PUT request
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: PUT");

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

$id = $data['id'] ?? 0;
$name = $data['name'] ?? '';
$email = $data['email'] ?? '';

$conn = new mysqli("localhost", "root", "", "rest_api");

if ($conn->connect_error) {
    die(json_encode(["error" => "Connection failed"]));
}

$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
if ($conn->query($sql)) {
    echo json_encode(["message" => "User updated successfully"]);
} else {
    echo json_encode(["error" => "Failed to update user"]);
}
$conn->close();
?>

? Example JSON Requests

? View Code Example
// JSON payloads sent from client
{
  "name": "Alice",
  "email": "alice@example.com"
}

{
  "id": 2,
  "name": "Bob Updated",
  "email": "bob.updated@example.com"
}

? Live Output / Explanation

The server responds with a JSON message indicating whether the operation was successful. This response can be easily consumed by frontend frameworks or mobile apps.

? Use Cases

  • User registration APIs
  • Profile update systems
  • Admin dashboards
  • Mobile and SPA backends

✅ Tips & Best Practices

  • Always validate and sanitize user input
  • Use prepared statements to prevent SQL injection
  • Return proper HTTP status codes
  • Maintain consistent JSON responses

? Try It Yourself

  • Create an endpoint to insert multiple users in one request
  • Add PATCH support for partial updates
  • Test APIs using Postman or curl