How to connect Android with PHP, MySQL and JSON

Step by step tutorial on how to connect Android with PHP and MySQL using JSON. We will use a free web hosting platform to setup the server.

Reasons to connect Android with PHP and MySQL

An Android app may need to communicate over a remote server for several reasons:

  • To register (sign up) on to the remote server

  • To log in to the remote server

  • Perform other operations permitted to the client by the remote server

Thus, the primary reason of the communication is to send data to and retrieve data from the remote server. This tutorial is aimed at learning how to connect an Android app to a remote server machine. For this purpose, we have chosen a web server running some PHP script that interacts on a MySQL database.

Objective of this Tutorial

The objective of this tutorial is to create a signup app in Android that involves a screen to take some fields, e. g, full name, username, password, etc. as input from the user, send this data over internet to a remote website, and insert this data into a MySQL database with the help a simple PHP script.

Tutorial Organization

This tutorial is divided into two parts. The first part involves no android part. It will take care of:

  • setting up the website

  • creating the MySQL database with necessary fields

  • uploading the PHP script onto the site that will insert data into the MySQL database

The second part will totally handle the Android part. It will take care of:

  • creating the user interface to take input from the user

  • taking input from the user and sending it to the PHP script residing in the remote server

Part-1: The PHP and MySQL Part

Setting up the Web Site

To set up a server, we will take assistance from a free web hosting platform. In our case, it is We already have created a web site under it that supports PHP and MySQL. This is a free hosting site, and you are encouraged to try your one after finishing this tutorial.

Creating MySQL Database

After creating the website, login to the members’ portal using your login credentials:

000webhost login

After logging in, you will see the web site address you just created listed and two tools’ icon beside it:

  • The cPanel

  • The Website Builder

Choose cPanel from it.

CPanel and Website Builder

In cPanel, you will see several tools listed such as File Manager, phpMyAdmin, etc.

Select MySQL tool to check the name of the MySQL host. In our case, it is Now create a new database with the name of the format aXXXXXXX_YourDBName, create a user for it with the username of the format: aXXXXXXX_YourUserName where X is a digit. Then set the password for your username. We already created a database named a2957838_android with username a2957838_anduser.

Manage MySQL Databases

Now that we have created the database and a user for it let’s go back to cPanel and choose the phpMyAdmin tool from it. Select Enter phpMyAdmin link beside your database name to create the table in the database. In phpMyAdmin, create a table with the following script:

  `fullname` varchar(80) COLLATE latin1_general_ci NOT NULL,
  `username` varchar(20) COLLATE latin1_general_ci NOT NULL,
  `password` varchar(20) COLLATE latin1_general_ci NOT NULL,
  `phone` varchar(40) COLLATE latin1_general_ci NOT NULL,
  `email` varchar(50) COLLATE latin1_general_ci NOT NULL,
  COLLATE=latin1_general_ci AUTO_INCREMENT=61;

Done! We have created the MySQL database, a user for the database, and a table inside it to hold user information.

Creating the PHP Script

In this subsection, we will write a very simple PHP script that:

  • Takes some input data using HTTP GET method

  • Inserts these data into the MySQL database table that we created in the previous subsection

I assume that you are familiar with the PHP language. Let’s see the complete code first:


if (mysqli_connect_errno($con))
   echo '{"query_result":"ERROR"}';

$fullName = $_GET['fullname'];
$userName = $_GET['username'];
$passWord = $_GET['password'];
$phoneNumber = $_GET['phonenumber'];
$emailAddress = $_GET['emailaddress'];

$result = mysqli_query($con,"INSERT INTO user (fullname, username, password, phone, email) 
          VALUES ('$fullName', '$userName', '$passWord', '$phoneNumber', '$emailAddress')");

if($result == true) {
	echo '{"query_result":"SUCCESS"}';
	echo '{"query_result":"FAILURE"}';

Now the explanation follows. The $con variable clearly holds a connection to the database with:

  • Server name:

  • User name: a2957838_anduser

  • Password: mypassword123

  • Database name: a2957838_android

The program then takes values of the variables passed to this script using HTTP GET method. For test purpose, we will now pass these variables using our browser’s URL (we will see this shortly). Then the script runs a function to insert data into the MySQL database. It displays some message in JSON format (that we will use to extract information from our Android program) to indicate success/failure of the insert operation.

I have already uploaded this script to site under a public_html folder with name signup.php.

000webhost console

Now we can call this script with the URL If we append to this URL a ‘?’ mark and the variable values separated by ‘&’ sign, these values will be passed to the server by HTTP GET method.

Now, open your favorite browser, copy and paste the following URL into its address bar, and press Enter:[email protected]

What do we see?


It indicates that data is successfully inserted to the user table!

Note: To keep it simple, I have not checked things like:

  • Username duplicity

  • Blank input values, etc.

In a standard program, however, you have to write code to validate things like above.

Part-2: The Android Part

Now let’s begin developing the Android app that communicates to the PHP script we have written in the previous section. I have used Android Studio for this purpose and an emulator for testing.

This is a simple app that consists of:

  • A single XML layout (activity_main.xml)

  • A single activity (

  • And a class to process server communication (

Creating the Project

Open a new project in Android Studio with name PHPMySQL, default activity with name, default layout with name activity_main.xml and other default settings. The location of activity_mai.xml is in app/res/layout and the location of java files is in app/java/org.example.phpmysql in the project explorer.

Creating the Layout

In our layout file, there are five EditText fields for five input fields and one Button to submit the data. It’s a basic layout and requires no explanation.

Open activity_main.xml and paste the following code in it:


<ScrollView xmlns:android=""


            android:hint="Full name"
            android:inputType="textPersonName" />

        <requestFocus />

            android:hint="Username" />

            android:inputType="textPassword" />

            android:hint="Phone number"
            android:inputType="phone" />

            android:hint="E-mail address"
            android:inputType="textEmailAddress" />

            android:text="Sign up" />



After creating the layout, in design view, your IDE should look like in the following Screenshot.

Android-PHP-MySQL Project in Android Studio

The Main Activity

Our main activity performs following tasks:

  • Inflates layout activity_main.xml in method onCreate()

  • Defines instance variables for layout elements in method onCreate()

  • Extracts values from input fields in method signup()

  • Sends these values to SignupActivity class for further processing [in method signup()]

The complete code of file is given below:


package org.example.phpmysql;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText etFullName, etUserName, etPassword, etPhone, etEmail;

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        etFullName = (EditText) findViewById(;
        etUserName = (EditText) findViewById(;
        etPassword = (EditText) findViewById(;
        etPhone = (EditText) findViewById(;
        etEmail = (EditText) findViewById(;

    public void signup(View v) {
        String fullName = etFullName.getText().toString();
        String userName = etUserName.getText().toString();
        String passWord = etPassword.getText().toString();
        String phoneNumber = etPhone.getText().toString();
        String emailAddress = etEmail.getText().toString();

        Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
        new SignupActivity(this).execute(fullName, userName, passWord, phoneNumber, emailAddress);

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == {
            return true;

        return super.onOptionsItemSelected(item);

The main activity is a simple class, and the lines of code are self-explanatory. Only note this line in signup() method:

new SignupActivity(this).execute(fullName, userName, passWord, phoneNumber, emailAddress);

This line of code calls the SignupActivity class by passing full name, username, password, phone number and email fields to it. The SignupActivity class extends Android’s AyncTask class that runs user code in a separate thread, and it involves an execute() method that can take values from the calling portion. Processing these values, the class sends diagnostic Toast messages to the main activity, which we will see in the next subsection.

The Signup Activity

Now we will begin the most important part of this tutorial. In this subsection, we will create a class named SignupActivity in our project that asynchronously calls the PHP script that we wrote earlier in this tutorial. Here the term asynchronous call means that the PHP script is called in the background, in a separate thread, without imposing load to the UI thread that the user is interacting with. This functionality is achieved through Android’s AsyncTask class. Let’s go through the complete source code of the class.


package org.example.phpmysql;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;


public class SignupActivity extends AsyncTask<String, Void, String> {

    private Context context;

    public SignupActivity(Context context) {
        this.context = context;

    protected void onPreExecute() {


    protected String doInBackground(String... arg0) {
        String fullName = arg0[0];
        String userName = arg0[1];
        String passWord = arg0[2];
        String phoneNumber = arg0[3];
        String emailAddress = arg0[4];

        String link;
        String data;
        BufferedReader bufferedReader;
        String result;

        try {
            data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
            data += "&username=" + URLEncoder.encode(userName, "UTF-8");
            data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
            data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
            data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");

            link = "" + data;
            URL url = new URL(link);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            result = bufferedReader.readLine();
            return result;
        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());

    protected void onPostExecute(String result) {
        String jsonStr = result;
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                String query_result = jsonObj.getString("query_result");
                if (query_result.equals("SUCCESS")) {
                    Toast.makeText(context, "Data inserted successfully. Signup successfull.", Toast.LENGTH_SHORT).show();
                } else if (query_result.equals("FAILURE")) {
                    Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();

There are general import statements at the beginning. The class extends AsyncTask class. The class definition contains a private Context element that contains a reference to the activity from which it has been called (in this case the MainActivity). There are three superclass methods that are overridden:

  • onPreExecute()

  • doInBackground()

  • onPostExecute()


In onPreExecute() method usually some initialization tasks, like initializing a progress bar, showing some Toast messages, etc. can be performed. In our case we left this method empty.


The main task is performed in the doInBackground() method. Notice that it takes a String type resource argument arg0 that it receives via the execute() method call inside signup() method of our MainActivity. Inside the doInBackground() method the full name, username, password, etc. values are extracted from the argument arg0 and are concatenated to a String variable data. This data is then appended to the URL of the PHP script as GET variables, and an HTTP connection is opened with this URL:

link = "" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();

Then a BufferedReader is created with the InputStreamReader corresponding to this URL connection. Then data is read from the buffered reader object. This is actually, the JSON data that is returned by the PHP script. As specified by our PHP script, depending on the success/failure of the operation, this JSON data can hold either of the following values:

  • {"query_result":"ERROR"}

  • {"query_result":"SUCCESS"}

  • {"query_result":"FAILURE"}

This JSON data is then returned to the onPostExecute() method for post-execution processing.

Notice that the main task of sending data to and receiving data from the remote server is performed in this doInBackground() method.


The onPostExecute() method, as its name suggests, usually performs post execution activities like closing a progress dialog, displaying diagnostic messages, etc. In our case, this method parses the JSON data that it received from doInBackground() method, and shows various Toast messages indicating the success/failure of the signup process (data insertion to database).

Running the Application

Now that we have finished writing and composing everything, we are going to run our app now. We will run it in an emulator of Android Studio. Before that, a very important thing is to update our manifest file. Include following line before the <application> tag in AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />

The above line tells the operating system that we are going to use Internet in our application.

If we now run the app in an emulator, we will see the following screens:

android app in an emulator

And this screenshot shows the state of the MySQL database:

state of the MySQL database