Last updated on December 31st, 2019 at 03:22 pm

Note:- PHP MySQL is depreciated you need to use PHP MySQLi or PDO to create web services or else you can use Framework like CakePHP 3, Larvel you can check this post to create REST API with MySQL or in Framework

How to create REST API in PHP MYSQLi

Built REST API in CakePHP 3 Framework

Web services ( application services ) is one of the most important parts of today’s development where we centralized or data and allow the user to access that data from different sources like web, software, app, etc.. Web service provide Interoperability between two different languages.  Web service is easy to understand or to made we can easily create a web service of our website. There are numbers of method through which you can create your web service

  1. SOAP { Simple Object Access Protocol }.
  2. REST { Representational State Transfer }

Update: RestFul Web Services with PHP Mysqli

Download

We are going to create a web service using the REST method but I also give you a small overview of the SOAP method first.

What is SOAP?.

SOAP is the Simple Object Access Protocol based on XML so it easy to read. It is a simple XML based protocol to exchange data between two different languages.

What is REST?.

REST { Representational State Transfer } is a simple stateless architecture that generally runs over HTTP. The REST web service system produces a status code response in JSON or XML format.

Note. I update this post and use MySQLi to create REST service please follow this link to create web service using PHP MySQLi.

Create web services using REST is very easy and takes less time to make as compared to others.

REST support all most commonly used HTTP methods (GET, POST, PUT and DELETE). We use all these methods according to need.

Application using REST

Now I am going to create a small application using REST. In this application, we can create a SignUp, Get user Info and Update user status. Before creating this application it is recommended that you have a basic understanding of PHP, MYSQL, JSON. I later explain to you how we can use this in android to access data from PHP based web services.

Step 1. I hope that you already install WAMP or XAMPP on your computer.

Step 2.  Now we need to install chrome extension for testing or web service so I use Advanced REST Client.

REST Client is very useful to test or web service. You simply follow the link I mention above and install an extension in your Chrome browser.

Advance REST client installation

Step 3. Now we are going to create our database http://localhost/phpmyadmin .

--
-- Database: `tuts_rest`
--

create database IF NOT EXISTS `tuts_rest`

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `status` text NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Copy-paste this SQL query to your phpmyadmin-> SQL.

Step 4. Now we need to create a data handler file in PHP and URL where we can handle request information.

Code: confi.php

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('tuts_rest', $conn);

first, we need to connect to our database. Now we can create a file to save requested data to database

signup.php

Requested URL: http://localhost/aneh/rest/signup.php

<?php

// Include confi.php
include_once('confi.php');

if($_SERVER['REQUEST_METHOD'] == "POST"){
	// Get data
	$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
	$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
	$password = isset($_POST['pwd']) ? mysql_real_escape_string($_POST['pwd']) : "";
	$status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";

	// Insert data into data base
	$sql = "INSERT INTO `tuts_rest`.`users` (`ID`, `name`, `email`, `password`, `status`) VALUES (NULL, '$name', '$email', '$password', '$status');";
	$qur = mysql_query($sql);
	if($qur){
		$json = array("status" => 1, "msg" => "Done User added!");
	}else{
		$json = array("status" => 0, "msg" => "Error adding user!");
	}
}else{
	$json = array("status" => 0, "msg" => "Request method not accepted");
}

@mysql_close($conn);

/* Output header */
	header('Content-type: application/json');
	echo json_encode($json);

In signup page I did not add any validation you can add your validation here if you like the main and important thing in this page is

header(‘Content-type: application/JSON’);

we tell PHP that this page is returned as JSON, and we also use json_encode() to return our data in JSON format.

Now after this we need Advance Rest Client to send data to our page. Go to your chrome app store where you add your extensions

Launch Advance REST Client

click on Advance Rest client. Now add your request

url: http://localhost/aneh/rest/signup.php, Select the Request method, Click on  Add new vaule define your value and data in it and click on send.

Add data in forms

after doing all this you need send data to the server and this output like this

Send data to server
That all if you get done message!.

Now we get user info using the GET method. I create a new PHP file to get user info once you have command on this you easily work on a single page.

Info.php

Requester URL: URL: http://localhost/aneh/rest/info.php?uid=Request_ID

Load data from service using get method

<?php
	// Include confi.php
	include_once('confi.php');

	$uid = isset($_GET['uid']) ? mysql_real_escape_string($_GET['uid']) :  "";
	if(!empty($uid)){
		$qur = mysql_query("select name, email, status from `users` where ID='$uid'");
		$result =array();
		while($r = mysql_fetch_array($qur)){
			extract($r);
			$result[] = array("name" => $name, "email" => $email, 'status' => $status); 
		}
		$json = array("status" => 1, "info" => $result);
	}else{
		$json = array("status" => 0, "msg" => "User ID not define");
	}
	@mysql_close($conn);

	/* Output header */
	header('Content-type: application/json');
	echo json_encode($json);

In this, we pass user id in URL. Add this URL in Advance REST Client and click on send and get output like this:

{
status: 1
info: [1]
0:  {
name: "aneh tahkur"
email: "[email protected]"
status: "Cool!!"
}-
-
}

Now we can update user info using the PUT method. To read about the Put method follow this link.

status.php

Request URL: http://localhost/aneh/rest/status.php

Update user status

<?php

// Include confi.php
include_once('confi.php');

if($_SERVER['REQUEST_METHOD'] == "PUT"){
	$uid = isset($_SERVER['HTTP_UID']) ? mysql_real_escape_string($_SERVER['HTTP_UID']) : "";
	$status = isset($_SERVER['HTTP_STATUS']) ? mysql_real_escape_string($_SERVER['HTTP_STATUS']) : "";

	// Add your validations
	if(!empty($uid)){
		$qur = mysql_query("UPDATE  `tuts_rest`.`users` SET  `status` =  '$status' WHERE  `users`.`ID` ='$uid';");
		if($qur){
			$json = array("status" => 1, "msg" => "Status updated!!.");
		}else{
			$json = array("status" => 0, "msg" => "Error updating status");
		}
	}else{
		$json = array("status" => 0, "msg" => "User ID not define");
	}
}else{
		$json = array("status" => 0, "msg" => "User ID not define");
	}
	@mysql_close($conn);

	/* Output header */
	header('Content-type: application/json');
	echo json_encode($json);

In the above I am using the PUT method in PUT we access data like this: $_SERVER[‘HTTP_DATAVARIABLE’].

Sending PUT Request from Advance Rest Client.

Put request

In this, we add URL where we want to make the request and then select Request method PUT and then add the header as shown in the above image.

OutPut of above is

{
status: 1
msg: "Status updated!!."
}

This is a very simple and easy example of web service example.

Some Useful Post related to Webservices

Thanks!

Happy Coding.