-
Dalam sebuah server terdapat sebuah database yang terdiri dari tabel-tabel sebagai berikut:
Struktur Database MySQLNama 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, `genre` varchar(30) DEFAULT NULL, `price` float DEFAULT NULL, `publish_date` date DEFAULT NULL, `description` text, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `book` (`id`, `author`, `title`, `genre`, `price`, `publish_date`, `description`) VALUES ('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.'); - 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
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 ""; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "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."; foreach ($line as $key => $col_value) { echo "<$key>$col_value$key>"; } echo " "; } echo ""; mysql_free_result($result); } mysql_close($link); ?> - 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. Misalnya http://localhost/examples/restweb/books.php. Jika hasilnya berupa data XML seperti tampak pada gambar berikut, maka script books.php sudah berjalan dengan benar.
- 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:
- 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>Rest Web Services </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 "Tambah Buku"; // Perulangan untuk Memasukkan Data ke Dalam Tabel HTML foreach ($xml->book as $book) { echo "
"; } ?> </body> </html>ID ".$book->id." Author ".$book->author." Title ".$book->title." Genre ".$book->genre." Price ".$book->price." Publish Date ".$book->publish_date." Delete - 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>
</body> </html>Rest Web Services </head> <body> <?php include "koneksi.php"; if (isset ($_POST['id'])) { $url = 'http://localhost/examples/restweb/books.php'; $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); } ?> Lihat Buku" . $_POST['id'] . " " . $_POST['author'] ." " . $_POST['title'] ." " . $_POST['genre'] . " " . $_POST['price'] . " " . $_POST['publish_date'] . " " . $_POST['description'] . " - 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>Rest Web Services </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 = " "; // 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 "Kembali ke index.php"; ?> </body> </html>;" . $id . "
Implementasi REST dengan PHP (GET, POST, DELETE)
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.
