[GUIDE] Android Client-Server Communication (PHP-MYSQL REST API)

Search This thread

alobo

Senior Member
Mar 20, 2012
163
217
Waterloo
www.oadigital.ca
Hey XDA, this is my first guide and first proper contribution to the community!

I’m writing this because I've seen many people ask a variation of the question: “How can my app get information from a database?”

This guide is intended for those who have created their first app – it is assumed you have a working development environment and are reasonable comfortable with the Android SDK and Java. I'm also assuming little to no knowledge of PHP and MYSQL

This guide walks you through:
  1. Setting up a database and a PHP script
  2. Testing the server
  3. Accessing it from Android.
To make it relevant, we're going to use data that we might see in an actual app: First & Last Name, Age and Points.


Requirements:
  1. Android Device*
  2. Computer*
  3. Apache/PHP/MySQL Server – I use WAMP (for Windows) (PHP v 5.4)
  4. Postman Rest Client for Google Chrome
(*Both must be connected to the same network!)

This guide will help you setup a local server. If you want to host your script and database online, you will have to purchase paid hosting.

Let's get started!

First off, what is a RESTful service?
According to Wikipedia: A RESTful web API (also called a RESTful web service) is a web API implemented using HTTP and REST principles.


How it works:

picture.php


A breakdown of the steps:
  1. The client makes a request using a HTTP POST to a server
  2. The PHP script queries the MYSQL server
  3. The PHP script gets the SQL data
  4. The PHP script puts the data into an array and assigns keys for the values. The script then outputs the data as a JSON array. JSON (JavaScript Object Notation) is a standard for data exchange, and formats the data in a way both humans and computers can easily read.
  5. The app parses the JSON and displays the data.

Code!

Part 1: The Server
We’re going to start by setting up the server!

Install WAMP server. Leave the settings at the default values.

Start WAMP server and let it come online.
Try and open http://localhost/phpmyadmin/ - if you installed it correctly, you should be greeted by the phpMyAdmin welcome screen. We're going to be using phpMyAdmin to create our database.

picture.php



Creating the Database:

Create a database called ‘mytestdatabase’. Now click the SQL tab, paste in the following SQL Code and hit run. This will create a test table called ‘users’ and fill it with data.

The table contains 5 columns: id, FirstName, LastName, Age, Points. It has 6 rows of sample data.


SQL Code:
Code:
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 15, 2013 at 10:07 PM
-- Server version: 5.5.24-log
-- PHP Version: 5.3.13

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET      [user=714032]@old_[/user]CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET      [user=714032]@old_[/user]CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET      [user=714032]@old_[/user]COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `MyTestDatabase`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `FirstName` text NOT NULL,
  `LastName` text NOT NULL,
  `Age` int(11) NOT NULL,
  `Points` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `FirstName`, `LastName`, `Age`, `Points`) VALUES
(1, 'John', 'Doe', 25, 61),
(2, 'Glen', 'Willis', 55, 3145),
(3, 'Helen', 'Cook', 35, 1232),
(4, 'Karen', 'Johnson', 20, 6456),
(5, 'Bill', 'Cooper', 60, 3856),
(6, 'Mary', 'Gomez', 30, 5422);

/*!40101 SET CHARACTER_SET_CLIENT      [user=714032]@old_[/user]CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS      [user=714032]@old_[/user]CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION      [user=714032]@old_[/user]COLLATION_CONNECTION */;

Your database should now look like this:

picture.php



We’re now ready to move on to the PHP!

Open up your WWW directory (C:\wamp\www) and create a new folder called ‘clientservertest’. In this folder, create a file called ‘login.php’.
Paste the following code into the file. (The PHP code is commented so you can follow what is going on)


PHP:
<?php

	#Ensure that the client has provided a value for "FirstNameToSearch"
	if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){
		
		#Setup variables
		$firstname = $_POST["FirstNameToSearch"];
		
		#Connect to Database
		$con = mysqli_connect("localhost","root","", "mytestdatabase");
		
		#Check connection
		if (mysqli_connect_errno()) {
			echo 'Database connection error: ' . mysqli_connect_error();
			exit();
		}

		#Escape special characters to avoid SQL injection attacks
		$firstname = mysqli_real_escape_string($con, $firstname);
		
		#Query the database to get the user details.
		$userdetails = mysqli_query($con, "SELECT * FROM users WHERE FirstName = '$firstname'");

		#If no data was returned, check for any SQL errors
		if (!$userdetails) {
			echo 'Could not run query: ' . mysqli_error($con);
			exit;
		}

		#Get the first row of the results
		$row = mysqli_fetch_row($userdetails);

		#Build the result array (Assign keys to the values)
		$result_data = array(
			'FirstName' => $row[1],
			'LastName' => $row[2],
			'Age' => $row[3],
			'Points' => $row[4],
			);

		#Output the JSON data
		echo json_encode($result_data); 
	}else{
		echo "Could not complete query. Missing parameter"; 
	}
?>



Testing the Script:

Try accessing http://localhost/clientservertest/login.php from your browser. Do you get this message:

"Could not complete query. Missing parameter"

Then it’s working! The script is looking for a POST variable called “FirstNameToSearch” – we didn't provide any, so it did't work!
To finish testing the script, open the Postman-REST client.
Set it up like so:

Request URL: http://localhost/clientservertest/login.php
Type: POST
Key: FirstNameToSearch
Value: John

Hit send, and you should see this:
Code:
{"FirstName":"John","LastName":"Doe","Age":"25","Points":"61"}

Congrats – your server just returned a result! Try some of the other names in the database (Glen, Helen, Karen, Bill, Mary) and see how their data is returned.

Note: Before we move on to the Android section, we’re going to have to put our WAMP server online. Click the WAMP icon in the taskbar and select 'Put Online'.
Find your computers local network IP address and insert it into the URL like so: http://192.168.1.112/clientservertest/login.php

You should be able to access the script. If this doesn't work, try turning off your firewall - it could be blocking the server.


Part 2: Android
We’re now going to use our Android device to access the web server instead of the Postman client.

I'm not going to go into detail with the boilerplate UI code - I've attached the source code to this post so you can download the project files and browse through them.

Note: Android 3.x+ cannot perform Network operations on the main thread. To solve this, we have to multithread our program. To keep this as simple as possible, we’re going to use an AsyncTask. Again, the code for this can be found in the project download.

Inside of the AsyncTask, we have the most important code - where we create and execute a HTTP POST in Java.


Creating and Executing a HTTP POST in Java:
We have to first setup the name-value pairs for our POST variables. In this case, we use "FirstNameToSearch" as our Key.

Code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", strNameToSearch));


The following code sets up connection timeouts (15 seconds) and creates a HttpClient and HttpPost pointing to our url (http://192.168.1.112/clientservertest/login.php)

Code:
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();

//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);			

HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.112/clientservertest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

The following code executes the POST, gets the result and converts it to a string:

Code:
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

String result = EntityUtils.toString(entity);

Finally, the following code creates a JSON object from the result string and extracts our data:

Code:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);

//Retrieve the data from the JSON object
strFirstName = jsonObject.getString("FirstName");
strLastName = jsonObject.getString("LastName");
intAge = jsonObject.getInt("Age");
intPoints = jsonObject.getInt("Points");


picture.php



That's it. It's so simple!


Where do we take it from here?
This combination of PHP/MYSQL is quite powerful. I'd recommend that you learn more about these technologies and build upon the demo in this guide. PHP Tutorials & MySQL Tutorials

Ideas for practice apps:
  • Online notes application - Sync your notes to the cloud
  • Build an Activation Server - Users can activate an app with a key


Feedback
Please feel free to leave any followup questions, comments or suggestions! I'll try my best to respond!
You can find the source code over at GitHub. Have fun! (If you fix a bug, please send a pull request)


 

Attachments

  • ClientServerRESTDemo.zip
    913.8 KB · Views: 3,397
Last edited:

vijai2011

Retired Recognized Developer
Oct 24, 2011
1,000
498
Thanks for this amazing guide but I have a issue.I have my own table and columns.So I changed your php code according to that and when I do a post query in rest,I get all null.But if I do the same in phpmyadmin,I have results.
This is what I get in postman:
Code:
{"pid":null,"name":null,"UID":null,"mobile":null,"description":null,"created_at":null,"updated_at":null}
attached the output of phpmyadmin.

And my phpcode:
Code:
<?php

	#Setup variables
	$firstname = $_POST["FirstNameToSearch"];

	#Avoid SQL injection attacks
	$firstname = mysql_real_escape_string($firstname);
	
	#Connect to Database
	$con = mysql_connect("localhost","user","pass");
	if (!$con)
	{
		die('Could not connect');
	}

	#Select the test database
	mysql_select_db("mydb", $con);

	#Get the user details from the database
	$userdetails = mysql_query("SELECT * FROM mytable WHERE name = '$firstname'");

	#Catch any errors
	if (!$userdetails) {
		echo 'It seems the server is down.Please try later';
		exit;
	}

	#Get the first row of the results
	$row = mysql_fetch_row($userdetails);

	#Build the result array (Assign keys to the values)
	$result_data = array(
		'pid' => $row[1],
		'name' => $row[2],
		'UID' => $row[3],
		'mobile' => $row[4],
                'description' => $row[5],
                'created_at' => $row[6],
                'updated_at' => $row[7],
		);

	#Output the JSON data
	echo json_encode($result_data); 

?>
Thanks for help.

Edit: just found that your app is missing internet permission in manifest
Code:
<uses-permission android:name="android.permission.INTERNET" />
 
Last edited:
  • Like
Reactions: dukedusty

cyberbeast

Member
Aug 17, 2010
6
0
:thumbup::) :D

Thanks so much for this. I will try it out soon.

Sent from my HTC Explorer A310e using xda app-developers app
 
Last edited:

alobo

Senior Member
Mar 20, 2012
163
217
Waterloo
www.oadigital.ca
Thanks for this amazing guide but I have a issue.I have my own table and columns.So I changed your php code according to that and when I do a post query in rest,I get all null.But if I do the same in phpmyadmin,I have results.
This is what I get in postman:
Code:
{"pid":null,"name":null,"UID":null,"mobile":null,"description":null,"created_at":null,"updated_at":null}
attached the output of phpmyadmin.

Thanks for help.


I was able to reproduce the null result - it means that the result was not available in the database. You'll want to double check the value you are passing to the script in Postman. (When I used 'FirstNameToSearch' and 'test' - I got a correct result. However, when I used 'testa', I got a null result.)


You can try adding this into the PHP script to catch this problem:


Code:
#Get the first row of the results
$row = mysql_fetch_row($userdetails);

[B]#Check to see if a result was returned.
if(!$row){
	echo 'User does not exist';
	exit;
}[/B]


I also noticed a few things in your PHP script:

  1. In your screenshot, your table name appears to be 'Myapp', however in your PHP script, it looks like you are using 'mytable'
  2. When you build the result array at the end, you are trying to access a column that doesn't exist:


    This code tries to access an 8th column/index:
    Code:
    	'pid' => $row[1],
    	'name' => $row[2],
    	'UID' => $row[3],
    	'mobile' => $row[4],
            'description' => $row[5],
            'created_at' => $row[6],
            'updated_at' => $row[7],

    You only have seven columns, so it should be:

    Code:
    	'pid' => $row[0],
    	'name' => $row[1],
    	'UID' => $row[2],
    	'mobile' => $row[3],
            'description' => $row[4],
            'created_at' => $row[5],
            'updated_at' => $row[6],

Edit: just found that your app is missing internet permission in manifest
Code:
<uses-permission android:name="android.permission.INTERNET" />

Good catch - Thanks! I'll update the project asap.
 

vijai2011

Retired Recognized Developer
Oct 24, 2011
1,000
498
I was able to reproduce the null result - it means that the result was not available in the database. You'll want to double check the value you are passing to the script in Postman. (When I used 'FirstNameToSearch' and 'test' - I got a correct result. However, when I used 'testa', I got a null result.)

:snip:

Good catch - Thanks! I'll update the project asap.
That is not a error in table name because I just wanted to hide it out here but actually it got revealed in the screenshot :D.No issues will try your php code and correct my json array too.thanks


Sent from my GT-N7000 using xda app-developers app
 

vijai2011

Retired Recognized Developer
Oct 24, 2011
1,000
498
For some reason,the problem was caused by the mysql_real_escape_string.I commented that line and it is working now.
 
  • Like
Reactions: alobo

alobo

Senior Member
Mar 20, 2012
163
217
Waterloo
www.oadigital.ca
For some reason,the problem was caused by the mysql_real_escape_string.I commented that line and it is working now.

Now that's interesting.. I've never experienced a problem with that before.

I took a look at the PHP docs and found that mysql_real_escape_string() is depreciated - that could be contributing to the problem. I'll investigate this further and adjust the guide as necessary.

Thanks for sharing your solution!.
 
  • Like
Reactions: vijai2011

vijai2011

Retired Recognized Developer
Oct 24, 2011
1,000
498
Now that's interesting.. I've never experienced a problem with that before.

I took a look at the PHP docs and found that mysql_real_escape_string() is depreciated - that could be contributing to the problem. I'll investigate this further and adjust the guide as necessary.

Thanks for sharing your solution!.

Maybe you are using ancient php module :p.BTW Can I also put data into tables using your php and slightly modifying "mysql_query" and using post?Or should I use put along with mysql_query?If later is the solution,could give me the snippet of how a put variable looks?because I dono php and I was waiting for someone to write this guide because before I was connecting to db with JDBS which isnt safe.Thanks and sorry for the trouble.

Edit: I got it to work like I said.But only issue is the created at and updated at time stamp which is not the part of php nor the app.I will correct it from mysql.Thanks once again.Will be happy to trouble you soon lol...No dont take it serious BTW
 
Last edited:

alobo

Senior Member
Mar 20, 2012
163
217
Waterloo
www.oadigital.ca
Maybe you are using ancient php module :p.BTW Can I also put data into tables using your php and slightly modifying "mysql_query" and using post?Or should I use put along with mysql_query?If later is the solution,could give me the snippet of how a put variable looks?because I dono php and I was waiting for someone to write this guide because before I was connecting to db with JDBS which isnt safe.Thanks and sorry for the trouble.

Edit: I got it to work like I said.But only issue is the created at and updated at time stamp which is not the part of php nor the app.I will correct it from mysql.Thanks once again.Will be happy to trouble you soon lol...No dont take it serious BTW

Ha you beat me to it! I'll definitely try and add a section into the guide about updating tables. I appreciate your feedback on the guide, and I'm glad it helped you. Feel free to trouble me :)
 

objaa

Senior Member
Feb 16, 2012
76
1
Super, thx!
But please tell me what I'm doing wrong.
Code:

1chast.jpg

HttpResponse response = httpclient.execute(httppost); //throw...
2xhast.PNG


i save errors in log (attached)
pls help ;(
 

Attachments

  • log.txt
    3.2 KB · Views: 12
  • 1chast.jpg
    1chast.jpg
    28.4 KB · Views: 146
  • 2xhast.PNG
    2xhast.PNG
    8.7 KB · Views: 132
Last edited:

vijai2011

Retired Recognized Developer
Oct 24, 2011
1,000
498
Super, thx!
But please tell me what I'm doing wrong.
Code:

1chast.jpg

HttpResponse response = httpclient.execute(httppost); //throw...
2xhast.PNG


i save errors in log (attached)
pls help ;(

You are doing something on the main thread which actually has to be done in a different thread.I suspect its at line #119.If you show the entire code,somebody might point it out easily for you

Sent from my GT-N7000 using xda app-developers app
 

objaa

Senior Member
Feb 16, 2012
76
1
You are doing something on the main thread which actually has to be done in a different thread.I suspect its at line #119.If you show the entire code,somebody might point it out easily for you

Sent from my GT-N7000 using xda app-developers app


ok, all code:

package com.nsp.obja;

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myscreen);
post();
}

@override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

void post()
{
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", "wow"));

//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();

//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);

HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://www.xda-developers.com/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

String result = EntityUtils.toString(entity);
Toast.makeText(this, result.length(), Toast.LENGTH_LONG).show();

}
catch(Exception e)
{
Log.e("ClientServerDemoX", "Error: ", e);
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
 

Attachments

  • code.txt
    2.3 KB · Views: 17

objaa

Senior Member
Feb 16, 2012
76
1
You are doing something on the main thread which actually has to be done in a different thread.I suspect its at line #119.If you show the entire code,somebody might point it out easily for you

Sent from my GT-N7000 using xda app-developers app

Do post() in async because it has to do http request which needs to be done in another thread.


hoooww :crying::crying:
Thanks, I figured out and got the code page of our glorious forum :)
 
Last edited:

dbarrera

Senior Member
Jan 6, 2012
524
98
Guayaquil
dbarrerap.github.io
I'm having an issue while testing the Query... I'm using Firefox and using RESTClient for debugging... and testing whatever value, db always responds null (See attachment)...
 
Last edited:

vijai2011

Retired Recognized Developer
Oct 24, 2011
1,000
498
I'm having an issue while testing the Query... I'm using Firefox and using RESTClient for debugging... and testing whatever value, db always responds null (See attachment)...

Exactly what I experienced first time.Try after commenting the line which prevents mysql injection and see if it works.If you run latest mysql,the chances are probably that its the issue
 

dbarrera

Senior Member
Jan 6, 2012
524
98
Guayaquil
dbarrerap.github.io
Exactly what I experienced first time.Try after commenting the line which prevents mysql injection and see if it works.If you run latest mysql,the chances are probably that its the issue

Already tried that... No go... Had to write the whole thing using w3schools example code as base... Just resolved a couple minutes ago and completed the project (it can be viewed @ Github:CardManager (App) and cardmanager_json (Web Service, only principal.php is the one handling the whole thing))...

Maybe a good add to the tutorial would be to have a config.php file with the user, passwd, database and table data calling it through require_once()... The DBConexion and DBGestion files (in my github) are supposed to do that, but didn't work either (hence doing the principal.php code all over again)...
 

alobo

Senior Member
Mar 20, 2012
163
217
Waterloo
www.oadigital.ca
Already tried that... No go... Had to write the whole thing using w3schools example code as base... Just resolved a couple minutes ago and completed the project (it can be viewed @ Github:CardManager (App) and cardmanager_json (Web Service, only principal.php is the one handling the whole thing))...

Maybe a good add to the tutorial would be to have a config.php file with the user, passwd, database and table data calling it through require_once()... The DBConexion and DBGestion files (in my github) are supposed to do that, but didn't work either (hence doing the principal.php code all over again)...

Interesting.. I'll take a look at at your script, revisit the W3 tutorials, and then re-write mine. It's really rudimentary and tends to fail easily. I wanted to write about the config.php, however, I also wanted to keep this guide as simple as possible for newer users. Maybe I'll add in an advanced section.
I'll update the guide in a few days, as I'm right in the middle of exams :/

Thanks for the feedback!
 

Top Liked Posts

  • There are no posts matching your filters.
  • 41
    Hey XDA, this is my first guide and first proper contribution to the community!

    I’m writing this because I've seen many people ask a variation of the question: “How can my app get information from a database?”

    This guide is intended for those who have created their first app – it is assumed you have a working development environment and are reasonable comfortable with the Android SDK and Java. I'm also assuming little to no knowledge of PHP and MYSQL

    This guide walks you through:
    1. Setting up a database and a PHP script
    2. Testing the server
    3. Accessing it from Android.
    To make it relevant, we're going to use data that we might see in an actual app: First & Last Name, Age and Points.


    Requirements:
    1. Android Device*
    2. Computer*
    3. Apache/PHP/MySQL Server – I use WAMP (for Windows) (PHP v 5.4)
    4. Postman Rest Client for Google Chrome
    (*Both must be connected to the same network!)

    This guide will help you setup a local server. If you want to host your script and database online, you will have to purchase paid hosting.

    Let's get started!

    First off, what is a RESTful service?
    According to Wikipedia: A RESTful web API (also called a RESTful web service) is a web API implemented using HTTP and REST principles.


    How it works:

    picture.php


    A breakdown of the steps:
    1. The client makes a request using a HTTP POST to a server
    2. The PHP script queries the MYSQL server
    3. The PHP script gets the SQL data
    4. The PHP script puts the data into an array and assigns keys for the values. The script then outputs the data as a JSON array. JSON (JavaScript Object Notation) is a standard for data exchange, and formats the data in a way both humans and computers can easily read.
    5. The app parses the JSON and displays the data.

    Code!

    Part 1: The Server
    We’re going to start by setting up the server!

    Install WAMP server. Leave the settings at the default values.

    Start WAMP server and let it come online.
    Try and open http://localhost/phpmyadmin/ - if you installed it correctly, you should be greeted by the phpMyAdmin welcome screen. We're going to be using phpMyAdmin to create our database.

    picture.php



    Creating the Database:

    Create a database called ‘mytestdatabase’. Now click the SQL tab, paste in the following SQL Code and hit run. This will create a test table called ‘users’ and fill it with data.

    The table contains 5 columns: id, FirstName, LastName, Age, Points. It has 6 rows of sample data.


    SQL Code:
    Code:
    -- phpMyAdmin SQL Dump
    -- version 3.5.1
    -- http://www.phpmyadmin.net
    --
    -- Host: localhost
    -- Generation Time: Jun 15, 2013 at 10:07 PM
    -- Server version: 5.5.24-log
    -- PHP Version: 5.3.13
    
    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
    SET time_zone = "+00:00";
    
    
    /*!40101 SET      [user=714032]@old_[/user]CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
    /*!40101 SET      [user=714032]@old_[/user]CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
    /*!40101 SET      [user=714032]@old_[/user]COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
    /*!40101 SET NAMES utf8 */;
    
    --
    -- Database: `MyTestDatabase`
    --
    
    -- --------------------------------------------------------
    
    --
    -- Table structure for table `users`
    --
    
    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `FirstName` text NOT NULL,
      `LastName` text NOT NULL,
      `Age` int(11) NOT NULL,
      `Points` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
    
    --
    -- Dumping data for table `users`
    --
    
    INSERT INTO `users` (`id`, `FirstName`, `LastName`, `Age`, `Points`) VALUES
    (1, 'John', 'Doe', 25, 61),
    (2, 'Glen', 'Willis', 55, 3145),
    (3, 'Helen', 'Cook', 35, 1232),
    (4, 'Karen', 'Johnson', 20, 6456),
    (5, 'Bill', 'Cooper', 60, 3856),
    (6, 'Mary', 'Gomez', 30, 5422);
    
    /*!40101 SET CHARACTER_SET_CLIENT      [user=714032]@old_[/user]CHARACTER_SET_CLIENT */;
    /*!40101 SET CHARACTER_SET_RESULTS      [user=714032]@old_[/user]CHARACTER_SET_RESULTS */;
    /*!40101 SET COLLATION_CONNECTION      [user=714032]@old_[/user]COLLATION_CONNECTION */;

    Your database should now look like this:

    picture.php



    We’re now ready to move on to the PHP!

    Open up your WWW directory (C:\wamp\www) and create a new folder called ‘clientservertest’. In this folder, create a file called ‘login.php’.
    Paste the following code into the file. (The PHP code is commented so you can follow what is going on)


    PHP:
    <?php
    
    	#Ensure that the client has provided a value for "FirstNameToSearch"
    	if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){
    		
    		#Setup variables
    		$firstname = $_POST["FirstNameToSearch"];
    		
    		#Connect to Database
    		$con = mysqli_connect("localhost","root","", "mytestdatabase");
    		
    		#Check connection
    		if (mysqli_connect_errno()) {
    			echo 'Database connection error: ' . mysqli_connect_error();
    			exit();
    		}
    
    		#Escape special characters to avoid SQL injection attacks
    		$firstname = mysqli_real_escape_string($con, $firstname);
    		
    		#Query the database to get the user details.
    		$userdetails = mysqli_query($con, "SELECT * FROM users WHERE FirstName = '$firstname'");
    
    		#If no data was returned, check for any SQL errors
    		if (!$userdetails) {
    			echo 'Could not run query: ' . mysqli_error($con);
    			exit;
    		}
    
    		#Get the first row of the results
    		$row = mysqli_fetch_row($userdetails);
    
    		#Build the result array (Assign keys to the values)
    		$result_data = array(
    			'FirstName' => $row[1],
    			'LastName' => $row[2],
    			'Age' => $row[3],
    			'Points' => $row[4],
    			);
    
    		#Output the JSON data
    		echo json_encode($result_data); 
    	}else{
    		echo "Could not complete query. Missing parameter"; 
    	}
    ?>



    Testing the Script:

    Try accessing http://localhost/clientservertest/login.php from your browser. Do you get this message:

    "Could not complete query. Missing parameter"

    Then it’s working! The script is looking for a POST variable called “FirstNameToSearch” – we didn't provide any, so it did't work!
    To finish testing the script, open the Postman-REST client.
    Set it up like so:

    Request URL: http://localhost/clientservertest/login.php
    Type: POST
    Key: FirstNameToSearch
    Value: John

    Hit send, and you should see this:
    Code:
    {"FirstName":"John","LastName":"Doe","Age":"25","Points":"61"}

    Congrats – your server just returned a result! Try some of the other names in the database (Glen, Helen, Karen, Bill, Mary) and see how their data is returned.

    Note: Before we move on to the Android section, we’re going to have to put our WAMP server online. Click the WAMP icon in the taskbar and select 'Put Online'.
    Find your computers local network IP address and insert it into the URL like so: http://192.168.1.112/clientservertest/login.php

    You should be able to access the script. If this doesn't work, try turning off your firewall - it could be blocking the server.


    Part 2: Android
    We’re now going to use our Android device to access the web server instead of the Postman client.

    I'm not going to go into detail with the boilerplate UI code - I've attached the source code to this post so you can download the project files and browse through them.

    Note: Android 3.x+ cannot perform Network operations on the main thread. To solve this, we have to multithread our program. To keep this as simple as possible, we’re going to use an AsyncTask. Again, the code for this can be found in the project download.

    Inside of the AsyncTask, we have the most important code - where we create and execute a HTTP POST in Java.


    Creating and Executing a HTTP POST in Java:
    We have to first setup the name-value pairs for our POST variables. In this case, we use "FirstNameToSearch" as our Key.

    Code:
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", strNameToSearch));


    The following code sets up connection timeouts (15 seconds) and creates a HttpClient and HttpPost pointing to our url (http://192.168.1.112/clientservertest/login.php)

    Code:
    //Create the HTTP request
    HttpParams httpParameters = new BasicHttpParams();
    
    //Setup timeouts
    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
    HttpConnectionParams.setSoTimeout(httpParameters, 15000);			
    
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost httppost = new HttpPost("http://192.168.1.112/clientservertest/login.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    The following code executes the POST, gets the result and converts it to a string:

    Code:
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    
    String result = EntityUtils.toString(entity);

    Finally, the following code creates a JSON object from the result string and extracts our data:

    Code:
    // Create a JSON object from the request response
    JSONObject jsonObject = new JSONObject(result);
    
    //Retrieve the data from the JSON object
    strFirstName = jsonObject.getString("FirstName");
    strLastName = jsonObject.getString("LastName");
    intAge = jsonObject.getInt("Age");
    intPoints = jsonObject.getInt("Points");


    picture.php



    That's it. It's so simple!


    Where do we take it from here?
    This combination of PHP/MYSQL is quite powerful. I'd recommend that you learn more about these technologies and build upon the demo in this guide. PHP Tutorials & MySQL Tutorials

    Ideas for practice apps:
    • Online notes application - Sync your notes to the cloud
    • Build an Activation Server - Users can activate an app with a key


    Feedback
    Please feel free to leave any followup questions, comments or suggestions! I'll try my best to respond!
    You can find the source code over at GitHub. Have fun! (If you fix a bug, please send a pull request)


    3
    Additional Information

    Changelog

    November 3, 2013
    • Added a link to the GitHub repository.

    June 26, 2013
    • Updated PHP Code. It's more reliable and uses the newer MySQL APIs. Thanks to @dbarrera & @vijai2011

    July 7, 2013
    • Updated the Android project and added Internet permissions (ClientServerRESTDemo v2.zip)
    2
    If the PHP is available for public use, with that kind of mysql connection it's extremely prone to mysql injection, and even with escape, PDO is advised to be used.

    Prepared statements prevent all injections, and I've rewritten the relevant PHP here:

    Code:
    //setup variables
    	$firstname = trim($_POST["FirstNameToSearch"]); // trim the string to remove spaces from beginning and end (never trust the user)
    	
    //connect to Database
    	try // try will attempt a connection
    	{		
    		$con = PDO("mysql:host=localhost;dbname=mytestdatabase","username","password");
    	}
    	catch(PDOException $e) // catch an error if try fails, like wrong credentials or no db found
    	{
    		// stop execution and print the error
    		die("Error: ". $e->getMessage()) 
    	}
    	
    	// set PDO error mode to exception. errors will throw exceptions when encountered
    	$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    	// set charset, utf8 helps avoid issues
    	$con->exec("SET NAMES utf8");
    
    	// run your query and select only the columns that are needed, saves memory and makes understanding the database structure easier!
    	$query = $con->prepare("SELECT FirstName, LastName, Age, Points FROM users WHERE FirstName = ? LIMIT 1"); 
    	
    	// bind the query variable to the first ?-token in the query
    	$query->bindParam(1, $firstname); 
    	
    	// run the query
    	$query->execute(); 
    
    	echo json_encode($query->fetch()); // print the result encoded in json. fetch will return an array

    You can ask me for more info if there's anything unclear :)

    You can thank @vijai2011 for hinting me about the thread!
    2
    Changing the password to a more simple one fixed it. Thanks! I used the following line to change the password:
    Code:
    $ mysqladmin -u root -p'oldpassword' password newpass

    Yeah, your password had the $ character which for php is the variable declaring character...
    @Alkonic tonight I will try to separate the DoPOST class from the activity... This should help the code be reused for other activities within the same app (if needed)...

    Sent from my GT-S5830M using Tapatalk 2
    2
    Already tried that... No go... Had to write the whole thing using w3schools example code as base... Just resolved a couple minutes ago and completed the project (it can be viewed @ Github:CardManager (App) and cardmanager_json (Web Service, only principal.php is the one handling the whole thing))...

    Maybe a good add to the tutorial would be to have a config.php file with the user, passwd, database and table data calling it through require_once()... The DBConexion and DBGestion files (in my github) are supposed to do that, but didn't work either (hence doing the principal.php code all over again)...

    Interesting.. I'll take a look at at your script, revisit the W3 tutorials, and then re-write mine. It's really rudimentary and tends to fail easily. I wanted to write about the config.php, however, I also wanted to keep this guide as simple as possible for newer users. Maybe I'll add in an advanced section.
    I'll update the guide in a few days, as I'm right in the middle of exams :/

    Thanks for the feedback!