PHP Web Services Tutorial: Now, we try fetch data from database at server side. Send to client as array format. Before read this post, we must understand about sending array format in nusoap. You can read it at here. If you still don't understand about php webservices, you can read this base article.
For practice, we will build simple database about book. Follow this steps:
- Open your phpmyadmin by pointing your browser to http://localhost/phpmyadmin.
- Create new database baru, named "testdb".
- Create new table, named "book".
Fill fields of this table.
- Insert some example data. Click insert tab.
Then, write & insert some example data.
- Now, create file named "server_book.php" within www/test/nusoap.
- Enter following code:
<?
//call library
require_once ('lib/nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('getallbook');
// create the function
function getallbook()
{
$conn = mysql_connect('localhost','root','admin');
mysql_select_db('testdb', $conn);
$sql = "SELECT * FROM book";
$q = mysql_query($sql);
while($r = mysql_fetch_array($q)){
$items[] = array('cd'=>$r['cd'],
'title'=>$r['title'],
'author'=>$r['author'],
'publisher'=>$r['publisher']);
}
return $items;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
- Create a file named "client_book.php" as client within www/test/nusoap. Enter following code:
<?
require_once ('lib/nusoap.php');
$client = new soapclient('http://localhost:8048/test/nusoap/server_book.php');
$response = $client->call('getallbook');
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode.")</p>";
echo "String: ".$client->faultstring;
}
else
{
$r = $response;
$count = count($r);
?>
<table border="1">
<tr>
<th>Code</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
</tr>
<?
for($i=0;$i<=$count-1;$i++){
?>
<tr>
<td><?=$r[$i]['cd']?></td>
<td><?=$r[$i]['title']?></td>
<td><?=$r[$i]['author']?></td>
<td><?=$r[$i]['publisher']?></td>
</tr>
<?
}
?>
</table>
<?
}
?>
Now, point your browser to http://localhost/test/nusoap/client_book.php. You should get like this: