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.
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 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 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();
?>
// JSON payloads sent from client
{
"name": "Alice",
"email": "alice@example.com"
}
{
"id": 2,
"name": "Bob Updated",
"email": "bob.updated@example.com"
}
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.