CRUD Operation in MySQL Using PHP, Volley Android - Insert Data
Last Updated :
05 Aug, 2022
It is known that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS. SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease, and flexibility of use. The application is used for a wide range of purposes, including data warehousing, e-commerce, and logging applications. MySQL provides a set of some basic but most essential operations that will help you to easily interact with the MySQL database and these operations are known as CRUD operations.

In the previous article, we have seen creating a new SQL database in the PhpMydmin service. In this article, we will perform the Insert data operation. Before performing this operation first of all we have to create a new PHP script for adding new data to that database in our SQL Database.Â
Prerequisite: You should be having Postman installed in your system to test this PHP script.Â
Create a new PHP script for adding new data to that database in our SQL Database
We will be building a simple PHP script in which we will be used to add data to our SQL table which we have created in our previous article. Using this script we will be adding data to 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 addCourses.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";
// for testing the user name is root.
$username = "root";
// the password for testing is "blank"
$password = "";
// below is the name for our
// database which we have added.
$dbname = "id16310745_gfgdatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// an array to display response
$response = array();
// on below line we are checking if the body provided by user contains
// this keys as course name,course description and course duration
if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){
// if above three parameters are present then we are extracting values
// from it and storing it in new variables.
$courseName = $_POST['courseName'];
$courseDuration = $_POST['courseDuration'];
$courseDescription = $_POST['courseDescription'];
// after that we are writing an sql query to
// add this data to our database.
// on below line make sure to add your table name
// in previous article we have created our table name
// as courseDb and add all column headers to it except our id.
$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`, `courseDescription`) VALUES (?,?,?)");
$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription);
// on below line we are checking if our sql query is executed successfully.
if($stmt->execute() == TRUE){
// if the script is executed successfully we are
// passing data to our response object
// with a success message.
$response['error'] = false;
$response['message'] = "course created successfully!";
} else{
// if we get any error we are passing error to our object.
$response['error'] = true;
$response['message'] = "failed\n ".$conn->error;
}
} else{
// this method is called when user
// donot enter sufficient parameters.
$response['error'] = true;
$response['message'] = "Insufficient parameters";
}
// at last we are printing our response which we get.
echo json_encode($response);
?>
Â
Step 4: Getting URL for our 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/addCourses.php
Now we will be adding data in our SQL table with this URL in postman. Â
Step 5: Testing our PHP Script in PostmanÂ
For testing your PHP script select the POST method in postman as we will be posting data to 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 data to our SQL table. Â

After sending this request our data has been added to our SQL table. You can get to see the data added in the PhpMyAdmin console in the below screenshot. Â

Insert Data Operation
In the upper part, we have created a PHP script for adding data to our SQL table. Along with that we have also tested that script by adding data to it. In this part, we will integrate that in our Android App and add 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 simply adding course details from a simple form in our SQL table which we have created. For performing this operation we will be using the Volley library which is used for JSON parsing in Android. 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 Name-->
<EditText
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Name"
android:importantForAutofill="no"
android:inputType="text" />
<!--Edittext for getting course Duration-->
<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Duration in min"
android:importantForAutofill="no"
android:inputType="time" />
<!--Edittext for getting course Description-->
<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Course Description"
android:importantForAutofill="no"
android:inputType="text" />
<!--Button for adding your course to Firebase-->
<Button
android:id="@+id/idBtnSubmitCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Submit Course Details"
android:textAllCaps="false" />
</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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
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 courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating variable for button
private Button submitCourseBtn;
// creating a strings for storing our values from edittext fields.
private String courseName, courseDuration, courseDescription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);
submitCourseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// getting data from edittext fields.
courseName = courseNameEdt.getText().toString();
courseDescription = courseDescriptionEdt.getText().toString();
courseDuration = courseDurationEdt.getText().toString();
// validating the text fields if empty or not.
if (TextUtils.isEmpty(courseName)) {
courseNameEdt.setError("Please enter Course Name");
} else if (TextUtils.isEmpty(courseDescription)) {
courseDescriptionEdt.setError("Please enter Course Description");
} else if (TextUtils.isEmpty(courseDuration)) {
courseDurationEdt.setError("Please enter Course Duration");
} else {
// calling method to add data to Firebase Firestore.
addDataToDatabase(courseName, courseDescription, courseDuration);
}
}
});
}
private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {
// url to post our data
String url = "http://localhost/courseApp/addCourses.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) {
Log.e("TAG", "RESPONSE IS " + response);
try {
JSONObject jsonObject = new JSONObject(response);
// on below line we are displaying a success toast message.
Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
// and setting data to edit text as empty
courseNameEdt.setText("");
courseDescriptionEdt.setText("");
courseDurationEdt.setText("");
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(MainActivity.this, "Fail to get response = " + 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("courseName", courseName);
params.put("courseDuration", courseDuration);
params.put("courseDescription", courseDescription);
// 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: Â
You can get to see the data that has been added to your SQL table in the below screenshot. Â

Â
Similar Reads
CRUD Operation in MySQL Using PHP, Volley Android - Read Data
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 i
9 min read
How to Update Data in API using Volley in Android?
Prerequisite: JSON Parsing in Android using Volley LibraryHow to Post Data to API using Volley in Android? We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the V
5 min read
How to Post Data to API using Volley in Android?
We have seen reading the data from API using Volley request with the help of GET request in Android. With the help of GET Request, we can display data from API in JSON format and use that data inside our application. In this article, we will take a look at posting our data to API using the POST requ
5 min read
Android - Update Data in API using Volley with Kotlin
Android applications use APIs to get the data from servers in android applications. With the help of APIs, we can add, read, update and delete the data from our database using APIs. We can use Volley and Retrofit for consuming data from APIs within the android application. In this article, we will t
5 min read
How to Perform CRUD Operations in Room Database in Android?
Data from the app can be saved on users' devices in different ways. We can store data in the user's device in SQLite tables, shared preferences, and many more ways. In this article, we will take a look at saving data, reading, updating, and deleting data in Room Database on Android. We will perform
15+ min read
Making API Calls using Volley Library in Android
Volley is an HTTP library thatâs used for caching and making a network request in Android applications. It is an HTTP library that makes networking for Android apps easier and most importantly, faster. API stands for Application Programming Interface. It is a way for two or more computer programs to
4 min read
CRUD Operation in REST API using PHP
A REST (Representational State Transfer) API allows communication between a client and a server through HTTP requests. PHP, a widely used server-side scripting language, is well-suited for creating REST APIs due to its simplicity and rich ecosystem. This article provides a step-by-step guide on buil
5 min read
How to Post Data to API using Volley in Android using Jetpack Compose?
APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android
3 min read
Android - Update Data in API Using Volley with Jetpack Compose
APIs are used in android applications to access data from servers. We can perform various CRUD operations using these APIs within our database such as adding new data, updating data, and reading as well as updating data. In this article, we will take a look at How to Update Data in API using Volley
8 min read
JSON Parsing in Android using Volley Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specif
6 min read