Tutorial simple PHP kali akan membahas membuat Web service data Mahasiswa simple dengan PDO ( PHP Data Object). Sedikit tambahan, bahwa Web service itu berguna untuk mengakses/mengambil data dari Aplikasi luar tentunya dengan permission atau hak akses. 

Ok langsung saja kita mulai . Pertama siapkan databse dan table nya (mySQL) 
DB Name : test , Table : mhs
kira begini penampakan table nya. ( buat sendiri jg gampang kn :D)

idnamaalamatumur
1GanjarSt. Paris 89, Jakarta
24
2Mimin

Jl. Sudnari asri no 90,Bandung

22
Persiapan folder dan file-file di htdocs

  1. koneksi.php
  2. mhs.php
  3. web_service.php
  4. akses_web_service.php

taruh file-file diatas di 1 folder misalnya 'web-service' di htdocs.

Sekarang kita buat satu-satu kode nya.

koneksi.php
<?php
class Koneksi { //DB name : test
    protected $dns = "mysql:host=localhost;dbname=test"; protected $db_user = "root";
protected $db_pass = "";
protected $konek = "";

    public function getKon() {

try{

$db = new PDO($this->dns,$this->db_user,$this->db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($db===FALSE){

throw new Exception("Koneksi Gagal");

}else{

$this->konek = $db;
}

}catch(Exception $e){

echo "Error : ".$e->getMessage();
}
return $this->konek;
}

public function closeKon(){

$this->konek = NULL; //diskonek Koneksi
}
} /* Kita sekalian buat Class active record simple untuk fetch data ke DB */
class ActiveRecord extends Koneksi{

public function fetchObject($sql){

$clone = array();

try{
$data =  $this->getKon()->prepare($sql);
$data->setFetchMode(PDO::FETCH_INTO,$this);
$data->execute();  /* krena fetch ingin sbg Object, maka kita hrus clone hasilnya */
while($result = $data->fetch()){

$clone[] = clone $result;
}
$this->closeKon();

}catch(PDOException $e){
   
echo $e->getMessage();
}
return $clone;
}
}

mhs.php
<?php
require_once "koneksi.php";

class MhsWebService{
    
    protected $name;
    protected $umur;
    
    //misal API yg dikasih utk client
    protected $API = 'khss8363621';
    
    public function setName($name){
        
        $this->name = $name;
    }
    public function getName(){
        
        return $this->name;
    }
    
    public function setUmur($umur){
        
        $this->umur = $umur;
    }
    public function getUmur(){
        
        return $this->umur;
    }
    
    public function validateAPI($api){
        
        if($this->API !== $api)
            return false;
            
        return true;
    }
    
    
    public function getMhs(){
					
       $objAr= new ActiveRecord();
       
       /*Query blm pake bind params, silahkan edit sendiri*/
       $sql = "SELECT * FROM mhs WHERE 1=1  ";
          if($this->getName()){
                    
              $sql .=" AND nama LIKE '%{$this->getName()}%' ";
          }
          if($this->getUmur()){

            $sql .=" AND umur LIKE '%{$this->getUmur()}%' ";
          }
		
      return $objAr->fetchObject($sql);
       
    }	
}
web_service.php
<?php 

//tipe data nya json yah, klo mau xml silahkan ubah sendiri
header('Content-Type: application/json');

require_once "koneksi.php";
require_once "mhs.php"; //load Class MhsWebService

$hasil  = array();

$s_name = $_GET['name'];
$s_umur = $_GET['umur'];
$s_API  = $_GET['API'];

$mhs = new MhsWebService();

if($mhs->validateAPI($s_API)){
    
    //kirim params" nya
    $mhs->setName($s_name);
    $mhs->setUmur($s_umur);
    
    $data = $mhs->getMhs();
    //print_r($data);
    reset($data);
    $i=0;
    //saya pake while, klo mau foreach silahkan :D
    while(list(,$r) =  each($data)){
	
        $hasil[$i]['nama'] = $r->nama;
        $hasil[$i]['umur'] = $r->umur;
        $hasil[$i]['alamat'] = $r->alamat;
        
        ++$i;
    }
   
   //hanya utk flag saja
   $hasil['status'] = TRUE;
    
}else{
    
    $hasil['status'] = FALSE;
}

echo json_encode($hasil);

?>

akses_web_service.php
<html>
    <head>
       <style>
          body{width:200px}
       </style>
    </head>
    <body>
        
        <h2>MHS Web Service</h2>
        <hr/>
        <form method="get" action="">
            Name  : <input type="text" name="name"/>
            
            Umur  : <input type="text" name="umur"/>
            
            <button type="submit">Search</button>
        </form>
         <?php 
        
            if($_GET){
            
                $s_name= isset($_GET['name']) ? $_GET['name'] : '';
                $s_umur= isset($_GET['umur']) ? $_GET['umur'] : '';

                $url  = "http://".$_SERVER['HTTP_HOST']."/test_php/web_service.php?API=khss8363621&name={$s_name}&umur={$s_umur}";
                
                $fields = array(
                    'name' => $s_name,
                    'umur' => $s_umur
                );
                
                $data = http_build_query($fields);

                $context = stream_context_create(array(
                    'http' =>  array(
                        'method'  => 'GET',
                        'header'  => 'Content-type: application/x-www-form-urlencoded',
                        'content' => $data,
                    )
                ));

                $result = file_get_contents($url, false, $context);
                //decode json nya ke array
                $vr = json_decode($result,true);
                
                echo "<pre>";
                    print_r($vr);
                echo "</pre>";
            }
            
        
        ?>
    </body>
</html>

Di atas terlihat saya pakai file_get_contents   , silahkan gunakan method yg lain jika perlu. 

Output dari program diatas seperti ini




Masih dalam Array biasa, silahkan proses sendiri :D

Akses aplikasinya di browser
localhost/web-service/akses_web_service.php


Begitulah kira-kira :D

Happy Coding !!!!