Open In App
Related Articles

CRUD Operation in MySQL Using PHP, Volley Android – Read Data

Improve Article
Save Article
Like Article

In the previous article, we have performed the insert data operation. In this article, we will perform the Read data operation. Before performing this operation first of all we have to create a new PHP script for reading data from SQL Database

Prerequisite: You should be having Postman installed in your system to test this PHP script. 

Create a PHP script for reading data from My SQL Database

We will be building a simple PHP script in which we will be used to read data from our SQL table which we have created in our previous article. Using this script we will be reading data from our SQL table.  

Step by Step Implementation  

Step 1: Start your XAMPP server which we have seen starting in the previous article  

In the previous article, we have seen starting our XAMPP server and we also have created our database. In this article, we will be creating a script for adding data to our database.  

Step 2: Navigate to xampp folder  

Now we have to navigate to C drive in your pc and inside that check for the folder name as xampp. Inside that folder navigate to htdocs folder and create a new folder in that and name it as courseApp. Inside this folder, we will be storing all our PHP scripts. Now for writing your PHP script we can use any simple text editor. I am using VS code. After creating this folder we simply have to open this folder in VS code.  

Step 3: Creating a new PHP file 

After you open your folder in VS code, inside that folder we have to press a shortcut key as Ctrl+N our new file will be created. We have to save this file with the name readCourses.php and add the below code to it. Comments are added in the code to get to know in more detail.    


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "id16310745_gfgdatabase";
// connect with database demo
$conn = new mysqli($servername, $username, $password, $dbname);
 // an array to display response
 $response = array();
 // on below line we are checking if the parameter send is id or not.
     // if the parameter send from the user id then
     // we will search the item for specific id.
     $id = $_POST['id'];
        //on below line we are selecting the course detail with below id.
     $stmt = $conn->prepare("SELECT courseName,courseDescription,courseDuration FROM courseDb WHERE id = ?");
     $result = $stmt->execute();
   // on below line we are checking if our
   // table is having data with specific id.
   if($result == TRUE){
         // if we get the response then we are displaying it below.
         $response['error'] = false;
         $response['message'] = "Retrieval Successful!";
         // on below line we are getting our result.
         // on below line we are passing parameters which we want to get.
         // on below line we are fetching the data.
         // after getting all data we are passing this data in our array.
         $response['courseName'] = $courseName;
         $response['courseDescription'] = $courseDescription;
         $response['courseDuration'] = $courseDuration;
     } else{
         // if the id entered by user donot exist then
         // we are displaying the error message
         $response['error'] = true;
         $response['message'] = "Incorrect id";
 } else{
      // if the user donot adds any parameter while making request
      // then we are displaying the error as insufficient parameters.
      $response['error'] = true;
      $response['message'] = "Insufficient Parameters";
 // at last we are printing
 // all the data on below line.
 echo json_encode($response);

Step 4: Getting URL for your PHP script  

For getting the URL for our PHP script we simply have to type localhost in our browser and we have to append it with our folder name and file name. You will get to see the URL highlighted below :  


Now we will be testing our API using Postman. 

Step 5: Testing our PHP Script in Postman

For testing your PHP script select the POST method in postman as we will be getting data from our SQL table and inside the URL section add the above URL. After adding the URL. Now click on the Body tab which is shown in the below screenshot and inside that select x-www-form-urlencoded and after that add the parameters in the below section as shown in the screenshot. Make sure the key which you are entering must be the same as that we have used for naming our columns in our SQL table. After adding all the data. Now click on Send option to send our id and receive data from our SQL table. 

You will get to see the response from the API on the above screen. 

Read Data Operation

In the upper part, we have created a PHP script for reading the data from the SQL table. In this part, we will integrate that in our Android App and read data to our SQL table from our Android app. 

What we are going to build in this article? 

We will be building a simple application in which we will be reading data from our SQL table by passing the ID. We will be reading this data using PHP scripts that we have created earlier. Below is the video in which we will get to see what we are going to build in this article. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add the below dependency in your build.gradle file

Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. 

implementation ‘’

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

Step 3: Adding permissions to the internet in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml and add the below code to it.   


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

Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 


<?xml version="1.0" encoding="utf-8"?>
    <!--Edit text for getting course id-->
        android:hint="Enter Course Id"
        android:inputType="number" />
    <!--Button for adding your course to Firebase-->
        android:text="Get Course Details"
        android:textAllCaps="false" />
            <!--Textview for displaying our Course Name-->
                android:textStyle="bold" />
            <!--Textview for displaying our Course Duration-->
                android:textColor="@color/black" />
            <!--Textview for displaying our Course Description-->
                android:textColor="@color/black" />

Step 5: Working with the file

Go to the file and refer to the following code. Below is the code for the file. Comments are added inside the code to understand the code in more detail.


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.cardview.widget.CardView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
    // creating variables for our edit text
    private EditText courseIDEdt;
    // creating variable for button
    private Button getCourseDetailsBtn;
    // creating variable for card view and text views.
    private CardView courseCV;
    private TextView courseNameTV, courseDescTV, courseDurationTV;
    protected void onCreate(Bundle savedInstanceState) {
        // initializing all our variables.
        courseNameTV = findViewById(;
        courseDescTV = findViewById(;
        courseDurationTV = findViewById(;
        getCourseDetailsBtn = findViewById(;
        courseIDEdt = findViewById(;
        courseCV = findViewById(;
        // adding click listener for our button.
        getCourseDetailsBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // checking if the id text field is empty or not.
                if (TextUtils.isEmpty(courseIDEdt.getText().toString())) {
                    Toast.makeText(MainActivity.this, "Please enter course id", Toast.LENGTH_SHORT).show();
                // calling method to load data.
    private void getCourseDetails(String courseId) {
        // url to post our data
        String url = "http://localhost/courseApp/readCourses.php";
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // on below line we are calling a string
        // request method to post the data to our API
        // in this we are calling a post method.
        StringRequest request = new StringRequest(Request.Method.POST, url, new<String>() {
            public void onResponse(String response) {
                try {
                    // on below line passing our response to json object.
                    JSONObject jsonObject = new JSONObject(response);
                    // on below line we are checking if the response is null or not.
                    if (jsonObject.getString("courseName") == null) {
                        // displaying a toast message if we get error
                        Toast.makeText(MainActivity.this, "Please enter valid id.", Toast.LENGTH_SHORT).show();
                    } else {
                        // if we get the data then we are setting it in our text views in below line.
                    // on below line we are displaying
                    // a success toast message.
                } catch (JSONException e) {
        }, new {
            public void onErrorResponse(VolleyError error) {
                // method to handle errors.
                Toast.makeText(MainActivity.this, "Fail to get course" + error, Toast.LENGTH_SHORT).show();
        }) {
            public String getBodyContentType() {
                // as we are passing data in the form of url encoded
                // so we are passing the content type below
                return "application/x-www-form-urlencoded; charset=UTF-8";
            protected Map<String, String> getParams() {
                // below line we are creating a map for storing our values in key and value pair.
                Map<String, String> params = new HashMap<String, String>();
                // on below line we are passing our key and value pair to our parameters.
                params.put("id", courseId);
                // at last we are returning our params.
                return params;
        // below line is to make
        // a json object request.

Now run your app and see the output of the code. 


Unlock the Power of Placement Preparation!
Feeling lost in OS, DBMS, CN, SQL, and DSA chaos? Our Complete Interview Preparation Course is the ultimate guide to conquer placements. Trusted by over 100,000+ geeks, this course is your roadmap to interview triumph.
Ready to dive in? Explore our Free Demo Content and join our Complete Interview Preparation course.

Last Updated : 23 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials