This section demonstrates how to create a READ API in PHP using the GET method to retrieve records from a database and return them in JSON format.
A PHP READ API connects to a database, executes a SELECT query, converts the result into an array, and outputs JSON using proper headers.
// Database connection and JSON response API
<?php
$host="localhost";
$user="root";
$pass="";
$dbname="rest_api";
$conn=new mysqli($host,$user,$pass,$dbname);
if($conn->connect_error){
die("Connection failed");
}
// Set JSON header
header("Content-Type: application/json");
$sql="SELECT id,name,email FROM users";
$result=$conn->query($sql);
$users=[];
while($row=$result->fetch_assoc()){
$users[]=$row;
}
// Return JSON output
echo json_encode($users);
$conn->close();
?>
// Sample JSON response returned by the API
[
{"id":1,"name":"Alice","email":"alice@example.com"},
{"id":2,"name":"Bob","email":"bob@example.com"},
{"id":3,"name":"Charlie","email":"charlie@example.com"}
]
This API can be tested directly in the browser or using tools like Postman by accessing the PHP file URL.