{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner
java,php,mobile,android,.net & windows

Tutorial: How to make a simple PHP webservice

Is this post ill shed some light on how to make a simple PHP webservice. This tutorial is the first in a serie that will show how to get data from your webserver to your Android application. This script will learn you the following:

XML output with php

itzz XML

  • Connect to a database ( MSaccess in this example )
  • Query the database
  • ReturnĀ XML
  • Explain how to use parameters

I have put alot of comments in the code to make it easy to understand :-)

//convert all the post data to php variables
foreach ($_POST as $key => $value) {
	$$key = addslashes(trim($value));
//check if a parameter exists - if not then we don't have to go to the database
if(isset($naam) || isset($plaats)):
	//open a msaccess connection
	$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");
	$cstr='Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.mdb;Jet OLEDB:System Database=C:\test.mdw;User ID=username;Password=hardtocrack!;';
	//Quit on error
	if (!$conn){exit("Connection Failed: " . $conn);}
	//to prevent SQL injection
	$n = addslashes($naam);
	$p = addslashes($plaats);
	//build the query
			naam Like "%' . $n . '%")
		AND plaats Like "%' . $p . '%");';
	//return an error in XML format if there is an error
	if (!$rs){	exit("<results status=\"error\"><message>Error in SQL</message></results>");}
	//loop thru the recordset and make up the results in XML format
	$num = 0;
	while (!$rs->EOF){
		  $id = $rs->Fields("id")->value;
		  $c = $rs->Fields("name")->value;
		  $n = $rs->Fields("plaats")->value;
		  $results .= "<result><orgid>$id</orgid><naam>$c</naam><plaats>$n</plaats></result>";
	//Wrap the results in a XML parent
	$retstr = "<results status=\"success\" count=\"$num\">";
	$retstr .= $results;
	$retstr .= "</results>";
	$rs->Close();	$rs = null;
	$conn->Close(); $conn = null;
	//return the XML data!
	echo str_replace("&", "en" ,$retstr);

Pretty straight forward code, inho :-) You can use any database you want ofcourse, i just decided to put up MS Access because a mysql / php is soo standard.

Example output will be:

<results status="success" count="2">
	<result><orgid>2</orgid><naam>p-xr</naam><plaats>Silicon Valley</plaats></result>

I hope you now are able to make a simple php webservice for yourself. In the next post we will explain how to make a http request from android and how we can secure this with a nice username/password :)

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks