PHP MySQL REST API for Android

PHP REST API backed up with a MySQL database is a very common schematic of an Enterprise mobile application. When the scenario requires data to be stored in a centralize manner, then this architecture should be used. Otherwise, the local database in the mobile can be used for storage and retrieval of information.

In this tutorial, we are creating a PHP RESTful service to read data from a (MySQL) database table. Also, I am providing an example Android project code for invoking this RESTful service. In a previous tutorial, we have seen then basics about PHP RESTful services. I strongly recommend you to go through it before continuing this tutorial.

In this example, we are calling the PHP REST API from an android application. In server side, the API service reads data from the database and sends the response in JSON format. After receiving the response, the Android application displays the row of items in a ListView.

PHP REST API that Reads MySQL Records

We have a database table containing the list of mobile phone model names. Our REST API fetches the list of mobile names from the database and sends the response in JSON. This REST API contains three parts. These are, the REST controller, service class, and the DAO.

RestController.php

The REST call lands on this controller. It calls the service to prepare a response.

Android App – PHP REST API Access

In this example, we are creating a simple Android app for accessing MySQL data using a REST API in PHP. We are having a ListView element in the MainActivity. We are creating a ListView Adapter to add the list of items returned as the API response. Then we set this adapter to the ListView element to display MySQL data rows.

On launching the MainActivity, we invoke the AsyncTask to access PHP MySQL REST API. We use “HTTPConnectionRequest” class to set params and send the request to the API. The following code shows the MainActivity class.