dev.rean.me
php

How to Create Simple PHP API with Database & Test with Postman in Khmer

Build a RESTful PHP API with MySQL database step-by-step and test endpoints using Postman with Khmer video tutorials.

2026-08-20 ยท 7 min read

Share:

Hello everyone! Today we will learn how to create Simple RESTful PHP API with MySQL database and test endpoints using Postman. Make sure you understand basic database operations from PHP CRUD with MySQL Database first! Very easy to follow with code examples and step-by-step video in Khmer!

I will explain step by step:

  1. Return JSON response from static PHP Array
  2. Setup MySQL database table (student_api)
  3. Build GET API (Fetch all students or get student by ID)
  4. Build POST API (Insert new student record)
  5. Build PUT API (Update student record)
  6. Build DELETE API (Soft delete record)

RESTFUL API (CRUD) with MySQL in Khmer

Step 1: Create Simple PHP API from Array

First, let's create a basic API that returns JSON data from a simple PHP array.

Example api_array.php:

<?php
// Set response header to JSON format
header("Content-Type: application/json");

$data = [
    ["id" => 1, "name" => "Reaskmey", "gender" => "Male"],
    ["id" => 2, "name" => "Nary", "gender" => "Female"],
];

// Check if user pass ID parameter in URL (?id=1)
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    foreach ($data as $row) {
        if ($row['id'] == $id) {
            echo json_encode($row, JSON_PRETTY_PRINT);
            exit;
        }
    }
    echo json_encode(["message" => "Student not found"]);
} else {
    // Return all data if no ID parameter
    echo json_encode($data, JSON_PRETTY_PRINT);
}
?>

๐Ÿ’ก Tip: ALWAYS add header("Content-Type: application/json"); at the top of your PHP API script so Postman, mobile apps, and frontend web apps recognize response as JSON!

Watch video: PHP API get data from array in Khmer

Step 2: Set Up MySQL Database & Table

Open phpMyAdmin in XAMPP or WAMP, create database named student_api, and run SQL query below to create students table:

CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    gender ENUM('Male', 'Female') NOT NULL,
    phone VARCHAR(20) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    address VARCHAR(255) NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Insert sample test data into students table:

INSERT INTO students (name, gender, phone, email, address) VALUES
('Sokha Chan', 'Male', '0123456789', 'sokha.chan@gmail.com', 'Phnom Penh'),
('Sophea Kim', 'Female', '0987654321', 'sophea.kim@gmail.com', 'Siem Reap'),
('Rithy Heng', 'Male', '0234567890', 'rithy.heng@gmail.com', 'Battambang'),
('Sreyneang Chum', 'Female', '0345678901', 'sreyneang.chum@gmail.com', 'Kampong Cham'),
('Piseth Sok', 'Male', '0456789012', 'piseth.sok@gmail.com', 'Sihanoukville');

๐Ÿ’ก Tip: Setting is_active TINYINT(1) DEFAULT 1 allows us to perform soft delete without losing historical database data!

Step 3: Connect Database & Create GET API

Now create api.php file inside htdocs folder.

Database connection setup:

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

$servername = "localhost";
$username   = "root";
$password   = ""; // Default XAMPP password is empty
$dbname     = "student_api";

$con = new mysqli($servername, $username, $password, $dbname);

if ($con->connect_error) {
    die(json_encode(["error" => "Database connection failed: " . $con->connect_error]));
}
?>

GET API implementation (Fetch All or Fetch by ID):

<?php
require_once "db.php";

// GET API endpoint
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $sql = "SELECT * FROM students WHERE id = $id AND is_active = 1";
} else {
    $sql = "SELECT * FROM students WHERE is_active = 1";
}

$result = $con->query($sql);
$response = [];

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $response[] = $row;
    }
    echo json_encode($response, JSON_PRETTY_PRINT);
} else {
    echo json_encode(["message" => "No student record found"]);
}
?>

๐Ÿ’ก Tip: Test http://localhost/api.php in browser or Postman GET method. Add ?id=1 to get single student record!

Watch video: Create PHP GET API read data from Database in Khmer

Step 4: Create PHP POST API (Insert Data)

POST API reads JSON body data sent from Postman or frontend input form.

POST API implementation:

<?php
require_once "db.php";

// Read raw JSON data sent from Postman body
$data = json_decode(file_get_contents('php://input'), true);

$name      = isset($data['name']) ? $data['name'] : "";
$gender    = isset($data['gender']) ? $data['gender'] : "";
$phone     = isset($data['phone']) ? $data['phone'] : "";
$email     = isset($data['email']) ? $data['email'] : "";
$address   = isset($data['address']) ? $data['address'] : "";

if (!empty($name) && !empty($email)) {
    $sql = "INSERT INTO students (name, gender, phone, email, address, is_active)
            VALUES ('$name', '$gender', '$phone', '$email', '$address', 1)";

    if ($con->query($sql) === TRUE) {
        echo json_encode(["message" => "Student inserted successfully!"]);
    } else {
        echo json_encode(["error" => "Insert failed: " . $con->error]);
    }
} else {
    echo json_encode(["message" => "Required fields (name, email) missing!"]);
}
?>

๐Ÿ’ก Tip: In Postman, select request method POST, select Body -> raw -> format JSON, and send data payload e.g. {"name": "Dara", "email": "dara@test.com"}.

Watch video: Create PHP POST API to Insert data in Khmer

Step 5: Create PHP PUT API (Update Data)

PUT method is used to update an existing record by student id.

PUT API implementation:

<?php
require_once "db.php";

// Read JSON input body
$data = json_decode(file_get_contents('php://input'), true);

$id      = isset($data['id']) ? intval($data['id']) : 0;
$name    = isset($data['name']) ? $data['name'] : "";
$phone   = isset($data['phone']) ? $data['phone'] : "";
$address = isset($data['address']) ? $data['address'] : "";

if ($id > 0) {
    $sql = "UPDATE students SET name = '$name', phone = '$phone', address = '$address' WHERE id = $id";

    if ($con->query($sql) === TRUE) {
        echo json_encode(["message" => "Student record updated successfully!"]);
    } else {
        echo json_encode(["error" => "Update failed: " . $con->error]);
    }
} else {
    echo json_encode(["message" => "Please provide valid student ID!"]);
}
?>

๐Ÿ’ก Tip: Use file_get_contents('php://input') to parse JSON body for PUT and DELETE requests because PHP $_POST superglobal only handles normal POST form requests!

Watch video: Create PHP PUT API to UPDATE data in Khmer

Step 6: Create PHP DELETE API (Soft Delete)

In real production APIs, soft deleting by changing status is_active = 0 is much safer than permanent DELETE FROM.

DELETE API implementation:

<?php
require_once "db.php";

$data = json_decode(file_get_contents('php://input'), true);
$id   = isset($data['id']) ? intval($data['id']) : 0;

if ($id > 0) {
    // Soft delete student record
    $sql = "UPDATE students SET is_active = 0 WHERE id = $id";

    if ($con->query($sql) === TRUE) {
        echo json_encode(["message" => "Student deleted (deactivated) successfully!"]);
    } else {
        echo json_encode(["error" => "Delete failed: " . $con->error]);
    }
} else {
    echo json_encode(["message" => "Please provide valid student ID!"]);
}
?>

๐Ÿ’ก Tip: Soft delete preserves database integrity so linked relational data (like orders or grades) do not become broken orphaned records!

Watch video: Create PHP DELETE API in Khmer

๐Ÿ’ก Series Wrap-up: Want to review your PHP environment setup? Check out How to Setup XAMPP and Essential VS Code Extensions for PHP!


That's it! You now built a complete PHP RESTful API with MySQL database and tested all CRUD endpoints in Postman! Happy coding! Sharing is caring!

โ† Back to php
Share: