Tutorial Implementasi REST Dengan PHP (GET, POST, DELETE) - Aditya Rizki's Blog PDF
Tutorial Implementasi REST Dengan PHP (GET, POST, DELETE) - Aditya Rizki's Blog PDF
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.
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";
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());
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:
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.
<html>
<head>
<title>Rest Web Services</title>
</head>
<body>
<?php
include "koneksi.php";
// Resources
$url =
'http://localhost/examples/restweb/books.php';
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>
<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();
$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>
<html>
<head>
<title>Rest Web Services</title>
</head>
<body>
<?php
include "koneksi.php";
$id = $_GET['id'];
echo $id;
$ch = curl_init();
$data = "<data><book>
<id>" . $id . "</id>
</book></data>";
curl_exec($ch);
curl_close($ch);
?>
</body>
</html>
Artikel lainnya:
Aditya Rizki / 24 July 2012 / Programming / PHP, xml, rest, web service, sql
d
WelcometoDisqus!Discovermoregreatdiscussionsjust
GetStarted
likethisone.We'realotmorethancomments.
Dismiss
9Comments AdityaRizki
1 ridims
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
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?