create PHP Rest API

Here is example of how create a rest API in PHP.

Employee table Schema

Create a 'test' MySQL database, if you have already any database then also run below sql into that database SQL query window.

CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
`employee_name` varchar(255) NOT NULL COMMENT 'employee name',
`employee_salary` double NOT NULL COMMENT 'employee salary',
`employee_age` int(11) NOT NULL COMMENT 'employee age',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;

MySQL Database Connection With PHP

We will create connection.php file and add MySQL connection string to connect MySQL with php using mysqli_connect() method. We will add below code into this file.

<?php
Class dbObj{
/* Database connection start */
var $servername = "localhost";
var $username = "root";
var $password = "";
var $dbname = "test";
var $conn;
function getConnstring() {
$con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$this->conn = $con;
}
return $this->conn;
}
}

?>

You need to replace database namedb usernamedb password and hostname as per your database information.

.htaccess Rewriterule with PHP for Clean URLs

We will create .htaccess file v1/ folder and write some rule to access rest api with pretty URLs.We will add following rules,

RewriteEngine On # Turn on the rewriting engine
RewriteRule ^employees/?$ employees.php [NC,L]
RewriteRule ^employees/([0-9]+)/?$ employees.php?id=$1 [NC,L]

Restful API to fetch all record from MySQL

We will create a GET type HTTP Rest Request to access all employee records from MySQL. We will use MySQL query to fetch data from employee table and send JSON data array to client as response object.

Now we will create employees.php file into v1 folder and add MySQL connection file to access database table data.

// Connect to database
include("../connection.php");
$db = new dbObj();
$connection = $db->getConnstring();

$request_method=$_SERVER["REQUEST_METHOD"];

I have also use $_SERVER method to access action information, like rest request for add, edit or delete.

We will create php switch method to access right method against action rest request.

switch($request_method)
{
case 'GET':
// Retrive Products
if(!empty($_GET["id"]))
{
$id=intval($_GET["id"]);
get_employees($id);
}
else
{
get_employees();
}
break;
default:
// Invalid Request Method
header("HTTP/1.0 405 Method Not Allowed");
break;
}

We have create GET request to fetch all employee data from mysql database, for single employee data we are passing employee id.We have define get_employees() method so we will create method like below,

function get_employees()
{
global $connection;
$query="SELECT * FROM employee";
$response=array();
$result=mysqli_query($connection, $query);
while($row=mysqli_fetch_array($result))
{
$response[]=$row;
}
header('Content-Type: application/json');
echo json_encode($response);
}

mysqli_query() method fetch data from MySQL employee table ans stored as abject into 'result'variable. The json_encode() method convert arrays of data into json string.

Now access http://localhost/api/v1/employees rest api url form browser and you will get a all employees record from mysql employee table.

Restful Api to get single record from MySQL using PHP

We will create a HTTP GET type rest request to access a single employee record from MySQL database using php. its same as previous rest call just passed employee id with in function.

function get_employees($id=0)
{
global $connection;
$query="SELECT * FROM employee";
if($id != 0)
{
$query.=" WHERE id=".$id." LIMIT 1";
}
$response=array();
$result=mysqli_query($connection, $query);
while($row=mysqli_fetch_array($result))
{
$response[]=$row;
}
header('Content-Type: application/json');
echo json_encode($response);
}

Now access http://localhost/api/v1/employees/1 rest api url form browser and you will get a single employee record from mysql employee table.

Rest Api to Create New Record into MySQL

We will create a new Rest Api to insert new employee record into MySQL using php. I will create POST type Rest request because We will post some JSON data to php server.

We will add new case into switch method like below,

case 'POST':
// Insert Product
insert_employee();
break;

Now we will create insert_employee() method into employees.php file.

function insert_employee()
{
global $connection;

$data = json_decode(file_get_contents('php://input'), true);
$employee_name=$data["employee_name"];
$employee_salary=$data["employee_salary"];
$employee_age=$data["employee_age"];
echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'";
if(mysqli_query($connection, $query))
{
$response=array(
'status' => 1,
'status_message' =>'Employee Added Successfully.'
);
}
else
{
$response=array(
'status' => 0,
'status_message' =>'Employee Addition Failed.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
}

Leave a Reply

Your email address will not be published. Required fields are marked *