web services in php

WEB SERVICES
Web services are using not by human beings, it is using from programs, softwares which are developed in different languages. These web services help to communicate between two software's.
Mainly these web services are made based on storing data and retrieving data.

/* this is the index page(index.php) of the web service */

<?php
include './functions.php';

        // headers to tell that result is JSON
        header("Content-Type:application/json");

        // process client request  via url
        // then process happpens

$a=customers();

// send the result now
echo json_encode($a);
?>

/* this is the function.php file, which includes in the index.php file */

function customers(){
//attributes to connect to the database
        $host="127.0.0.1";
$username="root";
$password="";
$db_name="shopdb";

        //establishing database connection
$connection=mysqli_connect("$host","$username","$password") or die("cannot identify the data base");

        //selecting and connecting to the database
mysqli_select_db($connection,$db_name) or die("cannot identify the database");

        //sql query which gives the data we want to access from the web service
$sql="SELECT * FROM customers";

        //executing the sql query
$result=mysqli_query($connection,$sql) or die(mysqli_error($connection));

        //creating an array to store the data which comes from the sql query execution.
        //this will be an associative array
$customer =array();
while($row = mysqli_fetch_array($result))
{
  $q= array(
'Customer id'=>$row['id'],
'Email'=>$row['email'],
'Mobile'=>$row['mobile_no'],
'Address'=>$row['address']
  );

array_push($customer,$q);

}
//closing the database connection
mysqli_close($connection);

        //returning the data array which we created with the data we got from the corresponding
//table(customers) table.
        return $customer;

        //this is to convert the displaying of the array in to JSON encode. in-built function in php
json_encode($customer);
}

/*out put of this code segment will be like this in JSON encoding*/
[{"Customer id":"102","Email":"0","Mobile":"775018380","Address":"colombo"},{"Customer id":"108","Email":"0","Mobile":"115246584","Address":"moratuwa"},{"Customer id":"245","Email":"0","Mobile":"115246844","Address":"moratuwa"}]

Comments

Popular posts from this blog

Dynamic Routing Demonstration Using CISCO PACKET TRACER and RIP

Containerize Java Application & Deploying on AWS Elastic Beanstalk