CRUD Operation in MySQL Using PHP, Volley Android - Read Data
Last Updated :
23 Jul, 2025
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.
PHP
<?php
$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($_POST['id']){
// 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 = ?");
$stmt->bind_param("s",$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.
$stmt->store_result();
// on below line we are passing parameters which we want to get.
$stmt->bind_result($courseName,$courseDescription,$courseDuration);
// on below line we are fetching the data.
$stmt->fetch();
// 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 :
http://localhost/courseApp/readCourses.php
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 ‘com.android.volley:volley:1.1.1’
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.
XML
<!--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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Edit text for getting course id-->
<EditText
android:id="@+id/idEdtCourseId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Enter Course Id"
android:importantForAutofill="no"
android:inputType="number" />
<!--Button for adding your course to Firebase-->
<Button
android:id="@+id/idBtnGetCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Get Course Details"
android:textAllCaps="false" />
<androidx.cardview.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/idCVCOurseItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:visibility="gone"
app:cardCornerRadius="6dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="vertical"
android:padding="4dp">
<!--Textview for displaying our Course Name-->
<TextView
android:id="@+id/idTVCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="CourseName"
android:textColor="@color/purple_500"
android:textSize="18sp"
android:textStyle="bold" />
<!--Textview for displaying our Course Duration-->
<TextView
android:id="@+id/idTVCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Duration"
android:textColor="@color/black" />
<!--Textview for displaying our Course Description-->
<TextView
android:id="@+id/idTVCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Description"
android:textColor="@color/black" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
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.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing all our variables.
courseNameTV = findViewById(R.id.idTVCourseName);
courseDescTV = findViewById(R.id.idTVCourseDescription);
courseDurationTV = findViewById(R.id.idTVCourseDuration);
getCourseDetailsBtn = findViewById(R.id.idBtnGetCourse);
courseIDEdt = findViewById(R.id.idEdtCourseId);
courseCV = findViewById(R.id.idCVCOurseItem);
// adding click listener for our button.
getCourseDetailsBtn.setOnClickListener(new View.OnClickListener() {
@Override
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();
return;
}
// calling method to load data.
getCourseDetails(courseIDEdt.getText().toString());
}
});
}
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 com.android.volley.Response.Listener<String>() {
@Override
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.
courseNameTV.setText(jsonObject.getString("courseName"));
courseDescTV.setText(jsonObject.getString("courseDescription"));
courseDurationTV.setText(jsonObject.getString("courseDuration"));
courseCV.setVisibility(View.VISIBLE);
}
// on below line we are displaying
// a success toast message.
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(MainActivity.this, "Fail to get course" + error, Toast.LENGTH_SHORT).show();
}
}) {
@Override
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";
}
@Override
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.
queue.add(request);
}
}
Now run your app and see the output of the code.
Output:
Similar Reads
PHP Tutorial PHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
9 min read
Basics
PHP SyntaxPHP, a powerful server-side scripting language used in web development. Itâs simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
4 min read
PHP VariablesA variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
5 min read
PHP | FunctionsA function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
PHP LoopsIn PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
4 min read
Array
PHP ArraysArrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
PHP Associative ArraysAn associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
4 min read
Multidimensional arrays in PHPMulti-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
5 min read
Sorting Arrays in PHPSorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
4 min read
OOPs & Interfaces
MySQL Database
PHP | MySQL Database IntroductionWhat is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
4 min read
PHP Database connectionThe collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
2 min read
PHP | MySQL ( Creating Database )What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
3 min read
PHP | MySQL ( Creating Table )What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
3 min read
PHP Advance
PHP SuperglobalsPHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
6 min read
PHP | Regular ExpressionsRegular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
12 min read
PHP Form HandlingForm handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the dataâeither through the POST method (more secure, hid
4 min read
PHP File HandlingIn PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
4 min read
PHP | Uploading FileHave you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
3 min read
PHP CookiesA cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
9 min read
PHP | SessionsA session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
7 min read