Home PHP Build REST Web Service with PHP, JSON and MySql
formats

Build REST Web Service with PHP, JSON and MySql

Web services is one of the most important part of today development where we centralized or data and allow user to access that data from different sources like mobile app,web etc.

Now days webservice are required with mobile development.There are no of method through which you can create you web service.

1. REST (Representational State Transfer)
2. SOAP (Simple Object Access Protocol)
3. XML-RPC (Remote Procedure Call uses XML)

Let ‘s give you some overview of the types.

1. REST (Representational State Transfer) : REST Web Services consist of using plain HTTP to make method calls and you get XML or JSON in response.Create webservice using REST is very easy and take less time to make as compare to other.
REST support all most commonly used HTTP methods (GET : Read, POST : Create, PUT : Update and DELETE : Delete).

2. SOAP (Simple Object Access Protocol): SOAP is Simple Object Access Protocol based on XML so it easy to read. It is simple XML based protocol to exchange data between two different language.

3. XML-RPC (Remote Procedure Call uses XML) : XML-RPC protocol is really simple. You pass requests which contain the method name, and parameters formatted in xml that defines their data types. The response comes back with similar xml data.

Here I am going to explain you how to create a basic web service using REST.In this application we can create a user , get user info,update user and delete user.

Before creating this web service you have basic knowledge about PHP,Mysql and JSON.

1. Install XAMPP OR WAMP in your system.

2. Now you need to create database. Here we create test database and create user table. (copy below code and paste in sql query)


— Database: `test`

create database IF NOT EXISTS `test`


— Table structure for table `users`

DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`status` enum(‘1′,’0’) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 

3. Create webservice folder Suppose are you using WAMP server then create like this folder D:/wamp/www/webservice Or For XAMPP server : D:\xampp\htdocs\webservice

4. Create file db_config.php for database configuration.In this file we need to connection to our database.
db_config.php :

<?php
$db_host = ‘localhost’; //hostname
$db_user = ‘root’; // username
$db_password = ”; // password
$db_name = ‘test’; //database name
$conn = mysql_connect($db_host, $db_user, $db_password );
mysql_select_db($db_name, $conn);

 

5. Now we can create a file to save requested data to database.
create.php :

<?php
/* include db.config.php */
include_once(‘db_config.php’);

if($_SERVER[‘REQUEST_METHOD’] == “POST”){
// Get post data`
$firstName = isset($_POST[‘firstname’]) ? mysql_real_escape_string($_POST[‘firstname’]) : “”;
$lastName = isset($_POST[‘lastname’]) ? mysql_real_escape_string($_POST[‘lastname’]) : “”;
$email = isset($_POST[’email’]) ? mysql_real_escape_string($_POST[’email’]) : “”;
$password = isset($_POST[‘password’]) ? mysql_real_escape_string($_POST[‘password’]) : “”;
$status = 0; // Here we set by default status In-active.
// Save data into database
$query = “INSERT INTO users (firstname,lastname,email,password,status) VALUES (‘$firstName’,’$lastName’,’$email’,’$password’,’$status’)”;
$insert = mysql_query($query);

if($insert){
$data = array(“result” => 1, “message” => “Successfully user added!”);
} else {
$data = array(“result” => 0, “message” => “Error!”);
}
} else {
$data = array(“result” => 0, “message” => “Request method is wrong!”);
}

mysql_close($conn);
/* JSON Response */
header(‘Content-type: application/json’);
echo json_encode($data);

 

6. In above code we did not add any validation you can add also validation code.

7. Now we need to install chrome extension for test web service. Here I am using Advanced REST client (https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo).

8. Now go to your chrome app store. Click on Advanced REST client.Now add your requests.
Here my url is http://localhost:8081/webservice/create.php

 

create_full

Done!

Now we get user information using GET method.I create new php file (select.php) to get user information.

1. select.php

<?php
/* include db.config.php */
include_once(‘db_config.php’);

// Get user id
$id = isset($_GET[‘id’]) ? mysql_real_escape_string($_GET[‘id’]) : “”;

if(empty($id)){
$data = array(“result” => 0, “message” => “Wrong user id Let ‘s try once again!”);
} else {
// get user data
$sql = “SELECT * FROM users where id=’$id'”;
$select = mysql_query($sql);
$result = array();
while($data = mysql_fetch_assoc($select)) {
$result[] = $data;
}

$data = array(“result” => 0, “data” => $result);
}

mysql_close($conn);
/* JSON Response */
header(‘Content-type: application/json’);
echo json_encode($data);

 

URL : http://localhost:8081/webservice/select.php?id=1

 

select_full

Now we update user information using PUT method.I create new php file (update.php) to update user information.

1. update.php

<?php
/* include db.config.php */
include_once(‘db_config.php’);

if($_SERVER[‘REQUEST_METHOD’] == “PUT”){

$id = isset($_SERVER[‘HTTP_ID’]) ? mysql_real_escape_string($_SERVER[‘HTTP_ID’]) : “”;
$firstName = isset($_SERVER[‘HTTP_FIRSTNAME’]) ? mysql_real_escape_string($_SERVER[‘HTTP_FIRSTNAME’]) : “”;
$lastName = isset($_SERVER[‘HTTP_LASTNAME’]) ? mysql_real_escape_string($_SERVER[‘HTTP_LASTNAME’]) : “”;
$email = isset($_SERVER[‘HTTP_EMAIL’]) ? mysql_real_escape_string($_SERVER[‘HTTP_EMAIL’]) : “”;
if(!empty($id)){
// Update data into database
$query = “UPDATE users SET firstname = ‘$firstName’,lastname = ‘$lastName’, email = ‘$email’ WHERE id = ‘$id'”;
$update = mysql_query($query);

if($update){
$data = array(“result” => 1, “message” => “Successfully user updated!”);
} else {
$data = array(“result” => 0, “message” => “Error!”);
}
} else {
$data = array(“result” => 0, “message” => “Wrong user id Let ‘s try once again!”);
}
} else {
$data = array(“result” => 0, “message” => “Request method is wrong!”);
}

mysql_close($conn);
/* JSON Response */
header(‘Content-type: application/json’);
echo json_encode($data);

 

We get PUT method value by $_SERVER[‘HTTP_VARIBLENAME’].

URL : http://localhost:8081/webservice/update.php

 

update_full

 

Now we delete user information using DELETE method.I create new php file (delete.php) to delete user.

1. delete.php

<?php
/* include db.config.php */
include_once(‘db_config.php’);

if($_SERVER[‘REQUEST_METHOD’] == “DELETE”){
// Get user id
$id = isset($_GET[‘id’]) ? mysql_real_escape_string($_GET[‘id’]) : “”;

if(empty($id)){
$data = array(“result” => 0, “message” => “Wrong user id Let ‘s try once again!”);
} else {
// get user data
$sql = “DELETE FROM users WHERE id = ‘$id'”;
$delete = mysql_query($sql);
if($delete){
$data = array(“result” => 1, “message” => “Successfully user deleted!”);
} else {
$data = array(“result” => 0, “message” => “Error!”);
}
}
} else {
$data = array(“result” => 0, “message” => “Request method is wrong!”);
}

mysql_close($conn);
/* JSON Response */
header(‘Content-type: application/json’);
echo json_encode($data);

URL : http://localhost:8081/webservice/delete.php?id=1

delete_full
 

Thank you! Let ‘s ROCK … 🙂

Share!Share on FacebookShare on Google+Share on LinkedInTweet about this on TwitterFlattr the authorDigg thisPin on PinterestEmail this to someoneShare on StumbleUponShare on RedditShare on TumblrBuffer this pagePrint this page
Tags:
Copyright © 2017 - Scalsys. All Rights Reserved