In the previous lessons, we learned how to retrieve all records and a single record using the GET method. Now we will learn how to create a new student using the HTTP POST method.
The HTTP POST method is commonly used to send data to a server for creating a new resource.
In our project, POST will be used to create a new student.
React Native
↓
POST Request
↓
PHP REST API
↓
MySQL
↓
New Student
| Method | Purpose |
|---|---|
| GET | Retrieve data |
| POST | Create new data |
GET is generally used for reading data, while POST is used to submit data to create a new resource.
We can use the same student endpoint for POST requests.
http://localhost/rest_api/api/students.php
The HTTP method tells the server what operation the client wants to perform.
Our API file can handle the POST request.
api/
students.php
The file can contain different logic depending on the HTTP request method.
PHP provides the HTTP request method through $_SERVER['REQUEST_METHOD'].
$method = $_SERVER['REQUEST_METHOD'];
We can check whether the request is a POST request.
if ($method === 'POST') {
// Create student
}
The API should return JSON responses.
header("Content-Type: application/json");
This tells the client that the API response is JSON.
The API needs a database connection to insert the new student.
require_once "../config/database.php";
This provides the PDO connection stored in $pdo.
REST APIs commonly receive POST data in JSON format.
PHP can read the raw request body using:
$input = file_get_contents("php://input");
The returned value is a string containing the request body.
The JSON request body can be converted into a PHP array using json_decode().
$data = json_decode(
file_get_contents("php://input"),
true
);
The second parameter true makes json_decode return an associative array.
A client can send student information like this:
{
"name": "Rahul",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "PHP"
}
The PHP API receives this JSON and converts it into a PHP array.
After decoding the JSON, we can access individual values.
$name = $data['name'] ?? '';
$email = $data['email'] ?? '';
$mobile = $data['mobile'] ?? '';
$course = $data['course'] ?? '';
The null coalescing operator provides an empty value if the key does not exist.
Before inserting data into the database, validate the required fields.
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
The SQL INSERT statement is used to create a new database record.
INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)
The question marks are placeholders for the values.
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)"
);
Prepared statements keep the SQL query separate from the supplied values.
Pass the received values to the prepared statement.
$stmt->execute([
$name,
$email,
$mobile,
$course
]);
If the query succeeds, a new student record is inserted into the table.
Our students table uses an AUTO_INCREMENT primary key.
id INT AUTO_INCREMENT PRIMARY KEY
Therefore, MySQL automatically generates the new student's ID when the record is inserted.
PDO provides lastInsertId() to retrieve the ID generated by an AUTO_INCREMENT column.
$student_id = $pdo->lastInsertId();
This ID can be included in the API response.
After successfully creating a student, the API can return HTTP status code 201 Created.
http_response_code(201);
echo json_encode([
"success" => true,
"message" => "Student created successfully",
"student_id" => $student_id
]);
<?php
header("Content-Type: application/json");
require_once "../config/database.php";
$data = json_decode(
file_get_contents("php://input"),
true
);
$name = $data['name'] ?? '';
$email = $data['email'] ?? '';
$mobile = $data['mobile'] ?? '';
$course = $data['course'] ?? '';
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)"
);
$stmt->execute([
$name,
$email,
$mobile,
$course
]);
$student_id = $pdo->lastInsertId();
http_response_code(201);
echo json_encode([
"success" => true,
"message" => "Student created successfully",
"student_id" => $student_id
]);
?>
Database operations can fail, so the INSERT operation should be handled with try-catch.
try {
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)"
);
$stmt->execute([
$name,
$email,
$mobile,
$course
]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Database error"
]);
}
<?php
header("Content-Type: application/json");
require_once "../config/database.php";
$data = json_decode(
file_get_contents("php://input"),
true
);
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$course = trim($data['course'] ?? '');
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
try {
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)"
);
$stmt->execute([
$name,
$email,
$mobile,
$course
]);
$student_id = $pdo->lastInsertId();
http_response_code(201);
echo json_encode([
"success" => true,
"message" => "Student created successfully",
"student_id" => $student_id
]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Database error"
]);
}
?>
Open Postman and select the POST method.
POST
http://localhost/rest_api/api/students.php
Then open the Body section and select:
raw
JSON
Enter the following JSON in the Postman request body:
{
"name": "Rahul",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "PHP"
}
Then click Send.
If the student is created successfully, the API can return:
{
"success": true,
"message": "Student created successfully",
"student_id": "3"
}
The generated ID depends on the records already present in the table.
After creating a student, you can use the Get All API to verify the record.
GET
http://localhost/rest_api/api/students.php
The newly created student should appear in the response.
Always check the API response and server logs when a POST request fails.
React Native / Postman
↓
POST Request
↓
JSON Request Body
↓
json_decode()
↓
Validate Data
↓
PDO Prepared Statement
↓
INSERT INTO students
↓
MySQL
↓
JSON Response
A React Native application can send a POST request when the user submits a registration or student form.
fetch("http://localhost/rest_api/api/students.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com",
mobile: "9876543210",
course: "PHP"
})
});
Never directly insert user-provided values into an SQL query. Use prepared statements instead.
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email, mobile, course)
VALUES (?, ?, ?, ?)"
);
$stmt->execute([
$name,
$email,
$mobile,
$course
]);
Prepared statements help protect database queries from SQL injection.
The POST API receives JSON data from the client, converts it into a PHP array, validates the required values, and inserts the new student into the MySQL database using a PDO prepared statement. The API then returns the newly created student ID as a JSON response.
POST
↓
JSON Body
↓
json_decode()
↓
Validation
↓
INSERT
↓
MySQL
↓
lastInsertId()
↓
JSON Response
Question: Which HTTP method is commonly used to create a new resource?