0% menganggap dokumen ini bermanfaat (0 suara)
130 tayangan17 halaman

Tutorial Implementasi REST Dengan PHP (GET, POST, DELETE) - Aditya Rizki's Blog PDF

Diunggah oleh

Bagus Nugroho
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
130 tayangan17 halaman

Tutorial Implementasi REST Dengan PHP (GET, POST, DELETE) - Aditya Rizki's Blog PDF

Diunggah oleh

Bagus Nugroho
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 17

Tutorial Implementasi REST dengan

PHP (GET, POST, DELETE)

Sebelum Anda belajar mengikuti tutorial implementasi REST ini, ada


baiknya Anda mengetahui konsep-konsep web service terlebih dahulu.
Saya pernah menuliskan sedikit terminologi REST dan SOAP web service
disini.

Implementasi REST dengan PHP dalam kasus ini akan mengambil contoh
sebuah sistem informasi buku yang didalamnya dapat memuat beberapa
aksi, diantaranya untuk menampilkan buku-buku terdaftar, input buku
terdaftar, serta menghapus buku yang terdaftar.

1. Dalam sebuah server terdapat sebuah database yang berisi tabel-tabel


sebagai berikut:

Struktur Database MySQL


Isi Database Example dengan nama tabel Book

Nama tabel: book (SQL dump)

CREATE TABLE IF NOT EXISTS `book` (


`id` varchar(5) NOT NULL DEFAULT '',
`author` varchar(30) DEFAULT NULL,
`title` varchar(30) DEFAULT NULL,
READMORE:
`genre` varchar(30) DEFAULT NULL,
`price` float DEFAULT NULL, Tutorial Basis Dat
`publish_date` date DEFAULT NULL, IV (Kesimpulan)
`description` text,
Berdasarkan stu
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1; denga MySQL m
Rancangan Bas
INSERT INTO `book` (`id`, `author`, `title`, `genre`, `price`,
Sosial yang tela
`publish_date`, `description`) VALUES
tutorial...
('1', 'Gambardella, Matthew', 'XML Developer''s Guide', 'Computer',
44.95, '2000-10-01', 'An in-depth look at creating applications\n
with XML.'),
('2', 'Ralls, Kim', 'Midnight Rain', 'Fantasy', 5.95, '2000-12-16',
'A former architect battles corporate zombies,\n an evil
sorceress, and her own childhood to become queen\n of the
world.'),
('666', 'Matthew Bellamy', 'Starlight', 'Fiction', 5, '2012-07-24',
'Book of fiction'),
('4', 'Marthen Lau', 'Mobile Web Design', 'Computer', 5.6, '2012-04-
24', 'mobile web design book'),
('18', 'Jaka', 'Jaka Sembung', 'Folks', 12, '2012-04-24', 'bagus'),
('17', 'Jaka', 'Jaka Sembung', 'Folks', 12, '2012-04-24', 'bagus'),
('21', 'Ralls, Kim', 'Midnight Rain', 'Fantasy', 5.95, '2012-04-24',
'A former architect battles corporate zombies, an evil
sorceress, and her own childhood to become queen of the
world.');
2. Agar database tersebut dapat digunakan untuk aplikasi yang berbeda,
maka data-data tersebut harus diubah ke dalam format data web service,
dalam hal ini menggunakan format XML. Berikut script REST-PHP untuk
melakukan metode-metode REST (GET, POST, dan DELETE), file ini
disimpan dengan nama books.php. Setting koneksi ke database diatur di
dalam script koneksi.php.

Script koneksi.php

<?php
// Koneksi ke Database
$link = mysql_connect('localhost', 'root', 'password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('nama_database') or die('Could not select
database');
?>

Script books.php

<?php
/*
* Copyright 2012
*/

//header untuk format XML, jika dihilangkan maka akan berbentuk data
String
header('Content-Type: text/xml; charset=ISO-8859-1');
include "koneksi.php";

// Check for the path elements


$path = $_SERVER[PATH_INFO];
if ($path != null) {
$path_params = spliti ("/", $path);
}

// METODE REQUEST untuk POST


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$input = file_get_contents("php://input");
$xml = simplexml_load_string($input);
foreach ($xml->book as $book) {
$querycek = "SELECT * FROM book WHERE id ='$book-
>id'";
$num_rows = mysql_num_rows($querycek);

if ($num_rows == 0)
{
$query = "INSERT INTO book (
id,
author,
title,
genre,
price,
publish_date,
description)
VALUES (
'$book->id',
'$book->author',
'$book->title',
'$book->genre',
'$book->price',
'$book->publish_date',
'$book->description')";

}
else if ($num_rows == 1)
{
$query = "UPDATE book SET

author = '$book->author',
title = '$book->title',
genre = '$book->genre',
price = '$book->price',
publish_date = '$book-
>publish_date',
description = '$book->description'
WHERE id = '$book->id'";

}
$result = mysql_query($query) or die('Query failed:
' . mysql_error());
}
// METODE REQUEST untuk DELETE
} else if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
$input = file_get_contents("php://input");
$xml = simplexml_load_string($input);
foreach ($xml->book as $book) {
$query = "DELETE FROM book WHERE id='$book->id'";
$result = mysql_query($query) or die('Query failed: ' .
mysql_error());

// METODE REQUEST untuk GET


} else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
if ($path_params[1] != null) {
$query = "SELECT
id,
author,
title,
genre,
price,
publish_date,
description
FROM book WHERE id =
$path_params[1]";
} else {
$query = "SELECT
id,
author,
title,
genre,
price,
publish_date,
description
FROM book ";
}
$result = mysql_query($query) or die('Query failed: ' .
mysql_error());

echo "<data>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<book>";
foreach ($line as $key => $col_value) {
echo "<$key>$col_value</$key>";
}
echo "</book>";
}
echo "</data>";

mysql_free_result($result);
}

mysql_close($link);

?>

Keterangan:

GET ~> untuk mengambil data XML

POST ~> untuk memasukkan data XML ke database (menambahkan


data)

DELETE ~> untuk menghapus node/data XML

nb: sebenarnya dalam REST dikenal juga istilah PUT, namun yang sering
digunakan adalah POST. Baik PUT dan POST dapat digunakan untuk melakukan
update data (edit data), namun hingga tulisan ini dibuat penulis belum tahu cara
mengmplementasikan PUT/POST untuk updating data.

3. Untuk mengecek apakah script books.php sudah dapat berkomunikasi


dengan database yang ada, coba panggil script books.php yang ada di
server masing-masing melalui browser.
Misalnyahttp://localhost/examples/restweb/books.php.Jika hasilnya berupa
data XML seperti tampak pada gambar berikut, maka script books.php
sudah berjalan dengan benar.
Pemanggilan Script books.php via browser

4. Kemudian cobalah untuk mengecek script.php lagi dengan mengakses


URL dengan cara menunjuk nomor ID-nya.
Misal:http://localhost/examples/restweb/books.php/1. Hasil yang keluar
seharusnya adalah data buku yang mempunya ID sama dengan 1.
Perhatikan hasilnya, sebagai berikut:
Pemanggilan Script books.php/1 via browser

5. Untuk menampilkan data XML ke dalam HTML (web browser), maka


diperlukan tag-tag HTML dikombinasikan dengan script books.php. Karena
berfungsi untuk menampilkan data saja, maka metode REST yang
dipanggil adalah GET. Perhatikan script index.php berikut:

<html>
<head>
<title>Rest Web Services</title>
</head>
<body>
<?php
include "koneksi.php";

// Resources
$url =
'http://localhost/examples/restweb/books.php';

// Mengambil Data String dari


Resources
$client = curl_init($url);
curl_setopt($client,
CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
curl_close($client);
$xml =
simplexml_load_string($response);

echo "<a href='tambah.php'>Tambah


Buku</a>";
// Perulangan untuk Memasukkan Data
ke Dalam Tabel HTML
foreach ($xml->book as $book)
{

echo "<table>
<tr>
<td>ID</td>
<td>".$book-
>id."</td>
</tr>
<tr>

<td>Author</td>
<td>".$book-
>author."</td>
</tr>
<tr>

<td>Title</td>
<td>".$book-
>title."</td>
</tr>
<tr>

<td>Genre</td>
<td>".$book-
>genre."</td>
</tr>
<tr>

<td>Price</td>
<td>".$book-
>price."</td>
</tr>
<tr>
<td>Publish
Date</td>
<td>".$book-
>publish_date."</td>
</tr>
<tr>

<td><a
href='delete.php?id=".$book->id."'>Delete</a></td>
</tr>
</table>
";
}
?>
</body>
</html>

Hasil tampilan index.php di browser:

Hasil tampilan index.php di browser


6. Di dalam script index.php tersebut terdapat hyperlink untuk Tambah
Data, jika di-klik maka akan memanggil script tambah.php. Script
tambah.php ini digunakan untuk menambahkan data. Untuk itu, metode
REST yang digunakan adalah POST. Perhatikan isi script tambah.php
berikut:

<html>
<head>
<title>Rest Web Services</title>
</head>
<body>

<?php
include "koneksi.php";

if (isset ($_POST['id'])) {

$url = 'http://localhost/examples/restweb/books.php';

$data = "<data><book>
<id>" . $_POST['id'] . "</id>
<author>" . $_POST['author'] ."</author>
<title>" . $_POST['title'] ."</title>
<genre>" . $_POST['genre'] . "</genre>
<price>" . $_POST['price'] . "</price>
<publish_date>" . $_POST['publish_date'] . "</publish_date>
<description>" . $_POST['description'] . "</description>
</book></data>";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);

curl_close($ch);
}

?>
<a href="index.php">Lihat
Buku</a>
<form method="POST"
action="tambah.php">
<table>
<tr>
<td>ID</td>
<td><input
type="text" name="id" id="id"></td>
</tr>
<tr>

<td>Author</td>
<td><input
type="text" name="author" id="author"></td>
</tr>
<tr>

<td>Title</td>
<td><input
type="text" name="title" id="title"></td>
</tr>
<tr>

<td>Genre</td>
<td><input
type="text" name="genre" id="genre"></td>
</tr>
<tr>

<td>Price</td>
<td><input
type="text" name="price" id="price"></td>
</tr>
<tr>
<td>Publish
Date</td>
<td><input
type="text" name="publish_date" id="date" value="<?php echo date("Y-
m-d"); ?>"></td>
</tr>
<tr>

<td>Description</td>
<td><input
type="text" name="description" id="description"></td>
</tr>
<tr>
<td><input
type="submit" name="submit" id="submit" value="Tambah"></td>
<td></td>
</tr>
</table>
</form>

</body>
</html>

Hasil tampilan tambah.php di browser:

Hasil tampilan tambah.php di browser:

7. Di dalam script index.php tersebut juga terdapat hyperlink untuk Delete,


jika di-klik maka akan memanggil script delete.php. Script delete.php ini
digunakan untuk menghapus data. Untuk itu, metode REST yang
digunakan adalah DELETE.Perhatikan isi script delete.php berikut:

<html>
<head>
<title>Rest Web Services</title>
</head>
<body>
<?php
include "koneksi.php";

$id = $_GET['id'];
echo $id;

// URL untuk service yang digunakan dalam hal ini


books.php dengan ID tertentu
$url =
'http://localhost/examples/restweb/books.php/'.$id.'';

$ch = curl_init();

$data = "<data><book>
<id>" . $id . "</id>
</book></data>";

// Bagian untuk memanggil request DELETE dari


books.php
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
curl_close($ch);

echo "<a href='index.php'>Kembali ke index.php</a>";

?>
</body>
</html>


Artikel lainnya:

Membuat Dokumen Web Service SOAP vs Perbedaan mysql dan


XML dengan PHP dan REST, Mana yang mysqli
MySQL Lebih Baik?

URL versi pendek untuk postingan ini yaitu: http://wp.me/p1kJe9-mh

Aditya Rizki / 24 July 2012 / Programming / PHP, xml, rest, web service, sql

d
WelcometoDisqus!Discovermoregreatdiscussionsjust
GetStarted
likethisone.We'realotmorethancomments.

Dismiss

9Comments AdityaRizki
1 ridims

Recommend Share SortbyBest

Jointhediscussion

WahyuDotPhp ayearago
tolongdonggan,kokbeginiya?
6 Reply Share

WanvySaputra>WahyuDotPhp 2monthsago
cobacekfilekoneksi.php.
1.rubahmysql_select_db('nama_database')menjadi
mysql_select_db('example')
2.hapuskata'password'
Reply Share

vennaky ayearago
gankenapaadaerrorextracontentya?bermasalahdiheaderXMLsama
path_paramsnyapadahaludahsamapersis,mohonpencerahanyahehe,btwnice
infogan
2 Reply Share

wirdanardi 3monthsago
makasihmas,sangatmembantusekali:)
Reply Share

RizaldiSatryaHerlambang 5monthsago
Mantabsmasadit,Lanjutkan!!:))))
Reply Share

AlietChaidir(Agga) 7monthsago
gan,kenapamalahblankyapasindex.php
gakeluardataatauerrorsamasekali
Reply Share

DedeYulia 8monthsago
Terimakasihtutorialnya,sangatmembantu.tapisayamaumenambahkanuntuk
vennakydanazizakhmad

1.settingphp.ini
rubahbarisdari:
cgi.fix_pathinfo=1

menjadi:

cgi.fix_pathinfo=1

2.rubahbooks.phpbaris1014
rubah:
//Checkforthepathelements
$path=$_SERVER[PATH_INFO]
if($path!=null){
$path_params=spliti("/",$path)
}
}

menjadi:
seemore

Reply Share

AdityaRizki Mod ayearago


DearAll,errortersebutbisajadikarenaversiwebserveryangsayagunakan
berbedadenganversiwebserveryangtemantemangunakan.Untuk
mengatasinyacobaGooglingyaataumasukkestackoverflow.com...)
Reply Share

azizakhmad ayearago
terimakasihganatassharenya,tapikokygbooks.phppunyakuerorpada
pengecekanpathnyalaluerorjugapadapath_params[1],tapisetelahanehapus
[1]padapath_params[1]hilangtuheror.kirakirakenapaya?
Reply Share

ALSOONADITYARIZKI WHAT'STHIS?

TutorialPemrogramanBerorientasi KerjaLepas
ObyekdenganC++:Multiple 1commentayearago
Inheritance(StudiKasus)
4commentsayearago merithopeMoshiMoshi,Halini
adminituuntukmemudahkan untukmemberitahukankepada
pemahamansaja,bisasajajikakitatanpa masyarakatumumbahwaNyonya,Merit
menggunakanmethod/fungsi...:D berharappemberipinjamankredit

MembacaJudulBukuMojok MenjajalPerangkatVirtualReality
1comment4monthsago denganGoogleCardboard
DanuSaputraMasAdit 1commentayearago
junjunganku..... putraSamsunggalaxygrandmuatgak
nih?

Subscribe d AddDisqustoyoursiteAddDisqusAdd Privacy

Aditya Rizki's Blog / Proudly powered by WordPress

Anda mungkin juga menyukai