Paramclasses Academy - Blog

Tutorials Details

←
Post 27 of 40
→

How to Send Form Data to a PHP and MySQL Backend from an Android App ?

How to Send Form Data to a PHP and MySQL Backend from an Android App ?

November 3, 2026

1. Introduction

Most modern Android applications need to communicate with a backend server.

For example:

  • A registration app sends user details to a server.

  • A shopping app sends order information to a database.

  • A login app sends email and password for authentication.

  • A school management app sends student records to a database.

In this tutorial, we will learn how to send data from an Android application to a PHP backend and store that data in a MySQL database.

We will build a practical Student Registration App.

The application will collect:

  • Student Name

  • Email Address

  • Mobile Number

When the user clicks the Register button, Android will send the data to a PHP API using an HTTP POST request. PHP will validate the data and insert it into MySQL.

2. Understanding the Application Architecture

Before writing code, understand how the application will work.

The complete data flow is:

  1. The user enters student details in the Android app.

  2. Android creates a JSON request.

  3. Android sends the request to a PHP API using HTTP POST.

  4. PHP receives and validates the JSON data.

  5. PHP connects to the MySQL database.

  6. PHP inserts the student record into MySQL.

  7. PHP returns a JSON response to Android.

  8. Android displays a success or error message.

The architecture contains three main components:

Android Application: Collects user input and sends data to the server.

PHP Backend: Receives requests, validates input and communicates with MySQL.

MySQL Database: Stores the student records.

3. Requirements

Make sure the following tools are available:

  1. Android Studio

  2. Java programming language

  3. XAMPP Server

  4. Apache

  5. MySQL

  6. Android Emulator or a real Android phone

Start Apache and MySQL from the XAMPP Control Panel.

We will use the Android Emulator to connect to the local XAMPP server.

4. Create a MySQL Database

First, open your browser and visit:

http://localhost/phpmyadmin/

Follow these steps:

  1. Open phpMyAdmin.

  2. Click the SQL tab.

  3. Execute the following SQL query.

CREATE DATABASE param_app;

USE param_app;

CREATE TABLE students (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,

    email VARCHAR(150) NOT NULL,

    mobile VARCHAR(15) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

Understanding the SQL Code

  • CREATE DATABASE creates a new database.

  • USE selects the database.

  • CREATE TABLE creates a student table.

  • id is the primary key.

  • AUTO_INCREMENT automatically generates a new ID.

  • name, email and mobile store student information.

  • created_at stores the record creation time.

Our database is now ready.

5. Create a PHP API

Now we will create a PHP backend that receives student information from Android.

Open your XAMPP installation folder.

Find the htdocs directory and create a new folder:

C:\xampp\htdocs\AndroidAPI

Inside this folder, create a PHP file:

db_connect.php

Step 1: Create the Database Connection

Add this code to db_connect.php:

<?php

$host = "localhost";
$dbname = "param_app";
$username = "root";
$password = "";

try {

    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );

    $pdo->setAttribute(
        PDO::ATTR_ERRMODE,
        PDO::ERRMODE_EXCEPTION
    );

} catch (PDOException $e) {

    http_response_code(500);

    header("Content-Type: application/json");

    echo json_encode([
        "status" => "error",
        "message" => "Database connection failed"
    ]);

    exit;
}

?>

Understanding the Database Connection

  • $host defines the database server.

  • $dbname defines the database name.

  • $username contains the MySQL username.

  • $password contains the MySQL password.

  • new PDO() creates a database connection.

  • PDO::ERRMODE_EXCEPTION enables exception-based error handling.

Important: The empty password shown here is only an example for a default local XAMPP setup. Use your actual database credentials. Never expose production database credentials in a public repository.

6. Create the Student Registration API

Inside the AndroidAPI folder, create another file:

register_student.php

Add the following code:

<?php

header("Content-Type: application/json");

require_once "db_connect.php";

// Receive JSON data from Android
$jsonData = file_get_contents("php://input");

$data = json_decode($jsonData, true);

// Check whether valid JSON was received
if (!is_array($data)) {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "Invalid JSON data"
    ]);

    exit;
}

// Receive student details
$name = trim($data["name"] ?? "");
$email = trim($data["email"] ?? "");
$mobile = trim($data["mobile"] ?? "");

// Validate input
if ($name === "" || $email === "" || $mobile === "") {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "All fields are required"
    ]);

    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "Invalid email address"
    ]);

    exit;
}

if (!preg_match('/^[0-9]{10,15}$/', $mobile)) {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "Invalid mobile number"
    ]);

    exit;
}

try {

    // Prepare SQL query
    $sql = "INSERT INTO students (name, email, mobile)
            VALUES (:name, :email, :mobile)";

    $stmt = $pdo->prepare($sql);

    // Execute query with user data
    $stmt->execute([
        ":name" => $name,
        ":email" => $email,
        ":mobile" => $mobile
    ]);

    // Get inserted student ID
    $studentId = $pdo->lastInsertId();

    http_response_code(201);

    echo json_encode([
        "status" => "success",
        "message" => "Student registered successfully",
        "student_id" => $studentId
    ]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "status" => "error",
        "message" => "Unable to save student data"
    ]);
}

?>

Understanding the PHP API

A. Receive JSON Data

$jsonData = file_get_contents("php://input");

This reads the raw request body sent by Android.

B. Convert JSON into a PHP Array

$data = json_decode($jsonData, true);

This converts the JSON request into a PHP associative array.

C. Get Student Details

$name = trim($data["name"] ?? "");
$email = trim($data["email"] ?? "");
$mobile = trim($data["mobile"] ?? "");

These statements extract the student details from the received data.

D. Validate the Email

filter_var($email, FILTER_VALIDATE_EMAIL);

This checks whether the email address has a valid format.

E. Prepare the SQL Query

$stmt = $pdo->prepare($sql);

This creates a prepared SQL statement.

Prepared statements help protect the database from SQL injection when user values are passed as parameters.

F. Insert the Record

$stmt->execute([
    ":name" => $name,
    ":email" => $email,
    ":mobile" => $mobile
]);

This executes the INSERT query using the received student details.

G. Return a JSON Response

echo json_encode([
    "status" => "success",
    "message" => "Student registered successfully"
]);

This sends a JSON response back to the Android application.

7. Test the PHP API

Before connecting Android, check whether the PHP files are accessible.

Open this URL in your browser:

http://localhost/AndroidAPI/register_student.php

Because this API expects a POST request containing JSON, opening it directly in a browser will not register a student. It may return an error response.

That is expected.

The actual registration request will be sent from our Android application.

8. Create an Android Studio Project

Now open Android Studio.

Follow these steps:

  1. Click New Project.

  2. Select Empty Views Activity.

  3. Enter the project name: StudentRegistrationApp.

  4. Select Java as the programming language.

  5. Select your minimum SDK.

  6. Click Finish.

Wait for Gradle sync to complete.

9. Add Internet Permission

Open:

app > manifests > AndroidManifest.xml

Add the INTERNET permission above the application tag:

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

For this local XAMPP demonstration, the emulator will connect through an HTTP address. Add the following attribute to the application tag:

android:usesCleartextTraffic="true"

Example:

<application
    android:allowBackup="true"
    android:label="StudentRegistrationApp"
    android:supportsRtl="true"
    android:usesCleartextTraffic="true">

    <!-- Activities -->

</application>

Security note: Allowing cleartext traffic is only for local testing. Production applications should use HTTPS and should not enable cleartext traffic globally.

10. Understand the Localhost Address

This is a very important step.

When using an Android Emulator, do not use:

http://localhost/AndroidAPI/register_student.php

Inside the emulator, localhost refers to the emulator itself, not your computer.

For the standard Android Emulator, use:

http://10.0.2.2/AndroidAPI/register_student.php

Here, 10.0.2.2 is the special address that allows the Android Emulator to access the host computer.

If you are using a real Android phone, use your computer's local network IP address instead. Both devices should be connected to the same Wi-Fi network, and the server firewall must allow the connection.

11. Design the Student Registration Screen

Open:

app > res > layout > activity_main.xml

Replace the existing layout with:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Student Registration"
            android:textSize="25sp"
            android:textStyle="bold"
            android:gravity="center"
            android:layout_marginBottom="25dp" />

        <EditText
            android:id="@+id/edtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Student Name"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/edtEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Email Address"
            android:inputType="textEmailAddress"
            android:layout_marginTop="12dp" />

        <EditText
            android:id="@+id/edtMobile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Mobile Number"
            android:inputType="phone"
            android:layout_marginTop="12dp" />

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register Student"
            android:layout_marginTop="25dp" />

        <TextView
            android:id="@+id/txtResult"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Registration result will appear here"
            android:textSize="16sp"
            android:layout_marginTop="20dp" />

    </LinearLayout>

</ScrollView>

Understanding the Layout

  • edtName collects the student's name.

  • edtEmail collects the email address.

  • edtMobile collects the mobile number.

  • btnRegister sends the information to the PHP API.

  • txtResult displays the server response.

  • ScrollView allows the screen to scroll when necessary.

12. Write Java Code to Send Data to PHP

Open:

app > java > your_package_name > MainActivity.java

Replace the existing code with:

package com.example.studentregistrationapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    EditText edtName, edtEmail, edtMobile;
    Button btnRegister;
    TextView txtResult;

    ExecutorService executorService;
    Handler mainHandler;

    String apiUrl =
            "http://10.0.2.2/AndroidAPI/register_student.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtName = findViewById(R.id.edtName);
        edtEmail = findViewById(R.id.edtEmail);
        edtMobile = findViewById(R.id.edtMobile);

        btnRegister = findViewById(R.id.btnRegister);
        txtResult = findViewById(R.id.txtResult);

        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());

        btnRegister.setOnClickListener(v -> {

            String name = edtName.getText().toString().trim();
            String email = edtEmail.getText().toString().trim();
            String mobile = edtMobile.getText().toString().trim();

            if (name.isEmpty() ||
                    email.isEmpty() ||
                    mobile.isEmpty()) {

                Toast.makeText(
                        this,
                        "Please fill all fields",
                        Toast.LENGTH_SHORT
                ).show();

                return;
            }

            sendStudentData(name, email, mobile);
        });
    }

    private void sendStudentData(
            String name,
            String email,
            String mobile
    ) {

        btnRegister.setEnabled(false);
        btnRegister.setText("Sending...");

        executorService.execute(() -> {

            HttpURLConnection connection = null;

            try {

                // Create JSON request
                JSONObject jsonObject = new JSONObject();

                jsonObject.put("name", name);
                jsonObject.put("email", email);
                jsonObject.put("mobile", mobile);

                // Open API connection
                URL url = new URL(apiUrl);

                connection = (HttpURLConnection)
                        url.openConnection();

                connection.setRequestMethod("POST");

                connection.setRequestProperty(
                        "Content-Type",
                        "application/json; charset=UTF-8"
                );

                connection.setRequestProperty(
                        "Accept",
                        "application/json"
                );

                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);
                connection.setDoOutput(true);

                // Send JSON data
                byte[] requestData = jsonObject.toString()
                        .getBytes(StandardCharsets.UTF_8);

                try (OutputStream outputStream =
                             connection.getOutputStream()) {

                    outputStream.write(requestData);
                    outputStream.flush();
                }

                // Read server response
                int responseCode =
                        connection.getResponseCode();

                InputStream inputStream;

                if (responseCode >= 200 &&
                        responseCode < 300) {

                    inputStream = connection.getInputStream();

                } else {

                    inputStream = connection.getErrorStream();
                }

                if (inputStream == null) {
                    throw new Exception(
                            "No response received from server"
                    );
                }

                StringBuilder response = new StringBuilder();

                try (BufferedReader reader =
                             new BufferedReader(
                                     new InputStreamReader(
                                             inputStream,
                                             StandardCharsets.UTF_8
                                     ))) {

                    String line;

                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                }

                JSONObject responseObject =
                        new JSONObject(response.toString());

                String status =
                        responseObject.optString("status");

                String message =
                        responseObject.optString(
                                "message",
                                "Unknown server response"
                        );

                mainHandler.post(() -> {

                    txtResult.setText(message);

                    Toast.makeText(
                            MainActivity.this,
                            message,
                            Toast.LENGTH_LONG
                    ).show();

                    if ("success".equals(status)) {

                        edtName.setText("");
                        edtEmail.setText("");
                        edtMobile.setText("");
                    }

                    btnRegister.setEnabled(true);
                    btnRegister.setText("Register Student");

                });

            } catch (Exception e) {

                mainHandler.post(() -> {

                    txtResult.setText(
                            "Error: " + e.getMessage()
                    );

                    Toast.makeText(
                            MainActivity.this,
                            "Unable to connect to server",
                            Toast.LENGTH_LONG
                    ).show();

                    btnRegister.setEnabled(true);
                    btnRegister.setText("Register Student");

                });

            } finally {

                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        executorService.shutdown();
    }
}

Important: If your project has a different package name, keep the package declaration generated by Android Studio.

13. Understand the Important Java Code

A. Create a JSON Object

JSONObject jsonObject = new JSONObject();

jsonObject.put("name", name);
jsonObject.put("email", email);
jsonObject.put("mobile", mobile);

This creates a JSON object containing the student details.

The resulting JSON will look like this:

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "mobile": "9876543210"
}

B. Set the HTTP Method

connection.setRequestMethod("POST");

POST is used because we are sending new student information to the server.

C. Set the Content Type

connection.setRequestProperty(
    "Content-Type",
    "application/json; charset=UTF-8"
);

This tells the PHP backend that the request body contains JSON data.

D. Send Data to the Server

outputStream.write(requestData);

This writes the JSON request body to the HTTP connection.

E. Read the Server Response

int responseCode = connection.getResponseCode();

This checks the HTTP response status.

A successful database insertion returns HTTP 201 Created from our PHP API.

F. Parse the JSON Response

JSONObject responseObject =
        new JSONObject(response.toString());

This converts the response text into a JSON object.

G. Display the Result

txtResult.setText(message);

This displays the message returned by the PHP backend.

14. Run the Complete Application

Now test the complete project.

Step 1: Open XAMPP Control Panel.

Step 2: Start Apache and MySQL.

Step 3: Confirm that your PHP files are available inside:

C:\xampp\htdocs\AndroidAPI\

The folder should contain:

AndroidAPI/
    db_connect.php
    register_student.php

Step 4: Open the Android application in your emulator.

Step 5: Enter sample student information:

Name: Rahul Kumar

Email: rahul@example.com

Mobile: 9876543210

Step 6: Click the Register Student button.

Step 7: Wait for the server response.

If everything works correctly, the app will display:

Student registered successfully

15. Verify Data in MySQL

Now open:

http://localhost/phpmyadmin/

Follow these steps:

  1. Select the param_app database.

  2. Open the students table.

  3. Click Browse.

You should see the newly registered student record.

You can also execute:

SELECT * FROM students;

This query displays all registered students.

Your Android application is now successfully connected to PHP and MySQL.

16. Common Errors and Their Solutions

Error 1: Connection Refused

Possible reason: Apache is not running or the API URL is incorrect.

Solution: Start Apache in XAMPP and verify the URL.

Error 2: Using Localhost in Android Emulator

Problem: Android cannot reach the computer's XAMPP server through the emulator's own localhost.

Solution: Use:

http://10.0.2.2/AndroidAPI/register_student.php

Error 3: Cleartext HTTP Traffic Not Permitted

Problem: Android blocks the local HTTP request.

Solution: For this local demonstration, configure android:usesCleartextTraffic="true" as explained earlier. Use HTTPS in production.

Error 4: Database Connection Failed

Possible reason: Database name, username or password is incorrect.

Solution: Check db_connect.php and confirm that MySQL is running.

Error 5: Data Is Not Inserted

Possible reason: The table name, column names or JSON keys do not match.

Solution: Verify the database schema and the PHP request fields.

Error 6: PHP Returns Invalid JSON

Possible reason: PHP warnings, notices or HTML error output are mixed with the JSON response.

Solution: Check the PHP error logs and ensure that the API returns only valid JSON.

Error 7: Real Phone Cannot Connect

Possible reason: The phone cannot reach the computer's local server.

Solution: Connect both devices to the same Wi-Fi network, use the computer's LAN IP address and check the firewall.

17. Security Best Practices

When developing real applications, follow these rules:

  1. Always use HTTPS in production.

  2. Validate input on the PHP server, even if Android also validates it.

  3. Use PDO prepared statements to prevent SQL injection.

  4. Never expose database credentials inside the Android application.

  5. Do not trust user input received from a mobile application.

  6. Avoid returning database passwords, SQL queries or internal server errors to users.

  7. Implement proper authentication and authorization for protected APIs.

  8. Store sensitive information securely.

  9. Apply appropriate request limits and server-side validation.

Remember: Android-side validation improves the user experience, but server-side validation is essential for data security.

18. Conclusion

In this tutorial, we successfully connected an Android application to a PHP and MySQL backend.

We created a Student Registration App that sends student details from Android to a PHP API and stores them in a MySQL database.

We learned:

  • Android to PHP communication.

  • HTTP POST requests.

  • JSON data creation and parsing.

  • PHP API development.

  • MySQL database connection using PDO.

  • Inserting records into MySQL.

  • Reading server responses in Android.

  • Testing APIs using XAMPP.

  • Handling common connection errors.

  • Basic API security practices.

This is an important foundation for building real-world Android applications with online databases.

19. Frequently Asked Questions

Q1. Can an Android application connect directly to MySQL?

Android applications should normally communicate with a backend API rather than connect directly to MySQL. The backend controls database access and validation.

Q2. Why do we use PHP between Android and MySQL?

PHP acts as the backend layer. It receives Android requests, validates data and executes database operations.

Q3. What is an HTTP POST request?

An HTTP POST request sends information to a server, commonly to create a new record.

Q4. Why do we use JSON?

JSON provides a structured and lightweight format for exchanging data between Android and PHP.

Q5. What is PDO in PHP?

PDO stands for PHP Data Objects. It provides a consistent interface for connecting to databases and executing queries.

Q6. Why do we use prepared statements?

Prepared statements safely pass user values into SQL queries and help prevent SQL injection.

Q7. Can the same PHP API work with multiple Android applications?

Yes. A properly designed backend API can serve multiple Android applications and other clients that follow the same API format.

Tutorial 27: How to Send Form Data to a PHP and MySQL Backend from an Android App

Param Classes – Android Studio & Java Tutorial Series
Module 7: APIs & Firebase

1. Introduction

Most modern Android applications need to communicate with a backend server.

For example:

  • A registration app sends user details to a server.

  • A shopping app sends order information to a database.

  • A login app sends email and password for authentication.

  • A school management app sends student records to a database.

In this tutorial, we will learn how to send data from an Android application to a PHP backend and store that data in a MySQL database.

We will build a practical Student Registration App.

The application will collect:

  • Student Name

  • Email Address

  • Mobile Number

When the user clicks the Register button, Android will send the data to a PHP API using an HTTP POST request. PHP will validate the data and insert it into MySQL.

2. Understanding the Application Architecture

Before writing code, understand how the application will work.

The complete data flow is:

  1. The user enters student details in the Android app.

  2. Android creates a JSON request.

  3. Android sends the request to a PHP API using HTTP POST.

  4. PHP receives and validates the JSON data.

  5. PHP connects to the MySQL database.

  6. PHP inserts the student record into MySQL.

  7. PHP returns a JSON response to Android.

  8. Android displays a success or error message.

The architecture contains three main components:

Android Application: Collects user input and sends data to the server.

PHP Backend: Receives requests, validates input and communicates with MySQL.

MySQL Database: Stores the student records.

3. Requirements

Make sure the following tools are available:

  1. Android Studio

  2. Java programming language

  3. XAMPP Server

  4. Apache

  5. MySQL

  6. Android Emulator or a real Android phone

Start Apache and MySQL from the XAMPP Control Panel.

We will use the Android Emulator to connect to the local XAMPP server.

4. Create a MySQL Database

First, open your browser and visit:

http://localhost/phpmyadmin/

Follow these steps:

  1. Open phpMyAdmin.

  2. Click the SQL tab.

  3. Execute the following SQL query.

CREATE DATABASE param_app;

USE param_app;

CREATE TABLE students (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,

    email VARCHAR(150) NOT NULL,

    mobile VARCHAR(15) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

Understanding the SQL Code

  • CREATE DATABASE creates a new database.

  • USE selects the database.

  • CREATE TABLE creates a student table.

  • id is the primary key.

  • AUTO_INCREMENT automatically generates a new ID.

  • name, email and mobile store student information.

  • created_at stores the record creation time.

Our database is now ready.

5. Create a PHP API

Now we will create a PHP backend that receives student information from Android.

Open your XAMPP installation folder.

Find the htdocs directory and create a new folder:

C:\xampp\htdocs\AndroidAPI

Inside this folder, create a PHP file:

db_connect.php

Step 1: Create the Database Connection

Add this code to db_connect.php:

<?php

$host = "localhost";
$dbname = "param_app";
$username = "root";
$password = "";

try {

    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );

    $pdo->setAttribute(
        PDO::ATTR_ERRMODE,
        PDO::ERRMODE_EXCEPTION
    );

} catch (PDOException $e) {

    http_response_code(500);

    header("Content-Type: application/json");

    echo json_encode([
        "status" => "error",
        "message" => "Database connection failed"
    ]);

    exit;
}

?>

Understanding the Database Connection

  • $host defines the database server.

  • $dbname defines the database name.

  • $username contains the MySQL username.

  • $password contains the MySQL password.

  • new PDO() creates a database connection.

  • PDO::ERRMODE_EXCEPTION enables exception-based error handling.

Important: The empty password shown here is only an example for a default local XAMPP setup. Use your actual database credentials. Never expose production database credentials in a public repository.

6. Create the Student Registration API

Inside the AndroidAPI folder, create another file:

register_student.php

Add the following code:

<?php

header("Content-Type: application/json");

require_once "db_connect.php";

// Receive JSON data from Android
$jsonData = file_get_contents("php://input");

$data = json_decode($jsonData, true);

// Check whether valid JSON was received
if (!is_array($data)) {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "Invalid JSON data"
    ]);

    exit;
}

// Receive student details
$name = trim($data["name"] ?? "");
$email = trim($data["email"] ?? "");
$mobile = trim($data["mobile"] ?? "");

// Validate input
if ($name === "" || $email === "" || $mobile === "") {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "All fields are required"
    ]);

    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "Invalid email address"
    ]);

    exit;
}

if (!preg_match('/^[0-9]{10,15}$/', $mobile)) {

    http_response_code(400);

    echo json_encode([
        "status" => "error",
        "message" => "Invalid mobile number"
    ]);

    exit;
}

try {

    // Prepare SQL query
    $sql = "INSERT INTO students (name, email, mobile)
            VALUES (:name, :email, :mobile)";

    $stmt = $pdo->prepare($sql);

    // Execute query with user data
    $stmt->execute([
        ":name" => $name,
        ":email" => $email,
        ":mobile" => $mobile
    ]);

    // Get inserted student ID
    $studentId = $pdo->lastInsertId();

    http_response_code(201);

    echo json_encode([
        "status" => "success",
        "message" => "Student registered successfully",
        "student_id" => $studentId
    ]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "status" => "error",
        "message" => "Unable to save student data"
    ]);
}

?>

Understanding the PHP API

A. Receive JSON Data

$jsonData = file_get_contents("php://input");

This reads the raw request body sent by Android.

B. Convert JSON into a PHP Array

$data = json_decode($jsonData, true);

This converts the JSON request into a PHP associative array.

C. Get Student Details

$name = trim($data["name"] ?? "");
$email = trim($data["email"] ?? "");
$mobile = trim($data["mobile"] ?? "");

These statements extract the student details from the received data.

D. Validate the Email

filter_var($email, FILTER_VALIDATE_EMAIL);

This checks whether the email address has a valid format.

E. Prepare the SQL Query

$stmt = $pdo->prepare($sql);

This creates a prepared SQL statement.

Prepared statements help protect the database from SQL injection when user values are passed as parameters.

F. Insert the Record

$stmt->execute([
    ":name" => $name,
    ":email" => $email,
    ":mobile" => $mobile
]);

This executes the INSERT query using the received student details.

G. Return a JSON Response

echo json_encode([
    "status" => "success",
    "message" => "Student registered successfully"
]);

This sends a JSON response back to the Android application.

7. Test the PHP API

Before connecting Android, check whether the PHP files are accessible.

Open this URL in your browser:

http://localhost/AndroidAPI/register_student.php

Because this API expects a POST request containing JSON, opening it directly in a browser will not register a student. It may return an error response.

That is expected.

The actual registration request will be sent from our Android application.

8. Create an Android Studio Project

Now open Android Studio.

Follow these steps:

  1. Click New Project.

  2. Select Empty Views Activity.

  3. Enter the project name: StudentRegistrationApp.

  4. Select Java as the programming language.

  5. Select your minimum SDK.

  6. Click Finish.

Wait for Gradle sync to complete.

9. Add Internet Permission

Open:

app > manifests > AndroidManifest.xml

Add the INTERNET permission above the application tag:

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

For this local XAMPP demonstration, the emulator will connect through an HTTP address. Add the following attribute to the application tag:

android:usesCleartextTraffic="true"

Example:

<application
    android:allowBackup="true"
    android:label="StudentRegistrationApp"
    android:supportsRtl="true"
    android:usesCleartextTraffic="true">

    <!-- Activities -->

</application>

Security note: Allowing cleartext traffic is only for local testing. Production applications should use HTTPS and should not enable cleartext traffic globally.

10. Understand the Localhost Address

This is a very important step.

When using an Android Emulator, do not use:

http://localhost/AndroidAPI/register_student.php

Inside the emulator, localhost refers to the emulator itself, not your computer.

For the standard Android Emulator, use:

http://10.0.2.2/AndroidAPI/register_student.php

Here, 10.0.2.2 is the special address that allows the Android Emulator to access the host computer.

If you are using a real Android phone, use your computer's local network IP address instead. Both devices should be connected to the same Wi-Fi network, and the server firewall must allow the connection.

11. Design the Student Registration Screen

Open:

app > res > layout > activity_main.xml

Replace the existing layout with:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Student Registration"
            android:textSize="25sp"
            android:textStyle="bold"
            android:gravity="center"
            android:layout_marginBottom="25dp" />

        <EditText
            android:id="@+id/edtName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Student Name"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/edtEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Email Address"
            android:inputType="textEmailAddress"
            android:layout_marginTop="12dp" />

        <EditText
            android:id="@+id/edtMobile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Mobile Number"
            android:inputType="phone"
            android:layout_marginTop="12dp" />

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register Student"
            android:layout_marginTop="25dp" />

        <TextView
            android:id="@+id/txtResult"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Registration result will appear here"
            android:textSize="16sp"
            android:layout_marginTop="20dp" />

    </LinearLayout>

</ScrollView>

Understanding the Layout

  • edtName collects the student's name.

  • edtEmail collects the email address.

  • edtMobile collects the mobile number.

  • btnRegister sends the information to the PHP API.

  • txtResult displays the server response.

  • ScrollView allows the screen to scroll when necessary.

12. Write Java Code to Send Data to PHP

Open:

app > java > your_package_name > MainActivity.java

Replace the existing code with:

package com.example.studentregistrationapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    EditText edtName, edtEmail, edtMobile;
    Button btnRegister;
    TextView txtResult;

    ExecutorService executorService;
    Handler mainHandler;

    String apiUrl =
            "http://10.0.2.2/AndroidAPI/register_student.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtName = findViewById(R.id.edtName);
        edtEmail = findViewById(R.id.edtEmail);
        edtMobile = findViewById(R.id.edtMobile);

        btnRegister = findViewById(R.id.btnRegister);
        txtResult = findViewById(R.id.txtResult);

        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());

        btnRegister.setOnClickListener(v -> {

            String name = edtName.getText().toString().trim();
            String email = edtEmail.getText().toString().trim();
            String mobile = edtMobile.getText().toString().trim();

            if (name.isEmpty() ||
                    email.isEmpty() ||
                    mobile.isEmpty()) {

                Toast.makeText(
                        this,
                        "Please fill all fields",
                        Toast.LENGTH_SHORT
                ).show();

                return;
            }

            sendStudentData(name, email, mobile);
        });
    }

    private void sendStudentData(
            String name,
            String email,
            String mobile
    ) {

        btnRegister.setEnabled(false);
        btnRegister.setText("Sending...");

        executorService.execute(() -> {

            HttpURLConnection connection = null;

            try {

                // Create JSON request
                JSONObject jsonObject = new JSONObject();

                jsonObject.put("name", name);
                jsonObject.put("email", email);
                jsonObject.put("mobile", mobile);

                // Open API connection
                URL url = new URL(apiUrl);

                connection = (HttpURLConnection)
                        url.openConnection();

                connection.setRequestMethod("POST");

                connection.setRequestProperty(
                        "Content-Type",
                        "application/json; charset=UTF-8"
                );

                connection.setRequestProperty(
                        "Accept",
                        "application/json"
                );

                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);
                connection.setDoOutput(true);

                // Send JSON data
                byte[] requestData = jsonObject.toString()
                        .getBytes(StandardCharsets.UTF_8);

                try (OutputStream outputStream =
                             connection.getOutputStream()) {

                    outputStream.write(requestData);
                    outputStream.flush();
                }

                // Read server response
                int responseCode =
                        connection.getResponseCode();

                InputStream inputStream;

                if (responseCode >= 200 &&
                        responseCode < 300) {

                    inputStream = connection.getInputStream();

                } else {

                    inputStream = connection.getErrorStream();
                }

                if (inputStream == null) {
                    throw new Exception(
                            "No response received from server"
                    );
                }

                StringBuilder response = new StringBuilder();

                try (BufferedReader reader =
                             new BufferedReader(
                                     new InputStreamReader(
                                             inputStream,
                                             StandardCharsets.UTF_8
                                     ))) {

                    String line;

                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                }

                JSONObject responseObject =
                        new JSONObject(response.toString());

                String status =
                        responseObject.optString("status");

                String message =
                        responseObject.optString(
                                "message",
                                "Unknown server response"
                        );

                mainHandler.post(() -> {

                    txtResult.setText(message);

                    Toast.makeText(
                            MainActivity.this,
                            message,
                            Toast.LENGTH_LONG
                    ).show();

                    if ("success".equals(status)) {

                        edtName.setText("");
                        edtEmail.setText("");
                        edtMobile.setText("");
                    }

                    btnRegister.setEnabled(true);
                    btnRegister.setText("Register Student");

                });

            } catch (Exception e) {

                mainHandler.post(() -> {

                    txtResult.setText(
                            "Error: " + e.getMessage()
                    );

                    Toast.makeText(
                            MainActivity.this,
                            "Unable to connect to server",
                            Toast.LENGTH_LONG
                    ).show();

                    btnRegister.setEnabled(true);
                    btnRegister.setText("Register Student");

                });

            } finally {

                if (connection != null) {
                    connection.disconnect();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        executorService.shutdown();
    }
}

Important: If your project has a different package name, keep the package declaration generated by Android Studio.

13. Understand the Important Java Code

A. Create a JSON Object

JSONObject jsonObject = new JSONObject();

jsonObject.put("name", name);
jsonObject.put("email", email);
jsonObject.put("mobile", mobile);

This creates a JSON object containing the student details.

The resulting JSON will look like this:

{
    "name": "Rahul Kumar",
    "email": "rahul@example.com",
    "mobile": "9876543210"
}

B. Set the HTTP Method

connection.setRequestMethod("POST");

POST is used because we are sending new student information to the server.

C. Set the Content Type

connection.setRequestProperty(
    "Content-Type",
    "application/json; charset=UTF-8"
);

This tells the PHP backend that the request body contains JSON data.

D. Send Data to the Server

outputStream.write(requestData);

This writes the JSON request body to the HTTP connection.

E. Read the Server Response

int responseCode = connection.getResponseCode();

This checks the HTTP response status.

A successful database insertion returns HTTP 201 Created from our PHP API.

F. Parse the JSON Response

JSONObject responseObject =
        new JSONObject(response.toString());

This converts the response text into a JSON object.

G. Display the Result

txtResult.setText(message);

This displays the message returned by the PHP backend.

14. Run the Complete Application

Now test the complete project.

Step 1: Open XAMPP Control Panel.

Step 2: Start Apache and MySQL.

Step 3: Confirm that your PHP files are available inside:

C:\xampp\htdocs\AndroidAPI\

The folder should contain:

AndroidAPI/
    db_connect.php
    register_student.php

Step 4: Open the Android application in your emulator.

Step 5: Enter sample student information:

Name: Rahul Kumar

Email: rahul@example.com

Mobile: 9876543210

Step 6: Click the Register Student button.

Step 7: Wait for the server response.

If everything works correctly, the app will display:

Student registered successfully

15. Verify Data in MySQL

Now open:

http://localhost/phpmyadmin/

Follow these steps:

  1. Select the param_app database.

  2. Open the students table.

  3. Click Browse.

You should see the newly registered student record.

You can also execute:

SELECT * FROM students;

This query displays all registered students.

Your Android application is now successfully connected to PHP and MySQL.

16. Common Errors and Their Solutions

Error 1: Connection Refused

Possible reason: Apache is not running or the API URL is incorrect.

Solution: Start Apache in XAMPP and verify the URL.

Error 2: Using Localhost in Android Emulator

Problem: Android cannot reach the computer's XAMPP server through the emulator's own localhost.

Solution: Use:

http://10.0.2.2/AndroidAPI/register_student.php

Error 3: Cleartext HTTP Traffic Not Permitted

Problem: Android blocks the local HTTP request.

Solution: For this local demonstration, configure android:usesCleartextTraffic="true" as explained earlier. Use HTTPS in production.

Error 4: Database Connection Failed

Possible reason: Database name, username or password is incorrect.

Solution: Check db_connect.php and confirm that MySQL is running.

Error 5: Data Is Not Inserted

Possible reason: The table name, column names or JSON keys do not match.

Solution: Verify the database schema and the PHP request fields.

Error 6: PHP Returns Invalid JSON

Possible reason: PHP warnings, notices or HTML error output are mixed with the JSON response.

Solution: Check the PHP error logs and ensure that the API returns only valid JSON.

Error 7: Real Phone Cannot Connect

Possible reason: The phone cannot reach the computer's local server.

Solution: Connect both devices to the same Wi-Fi network, use the computer's LAN IP address and check the firewall.

17. Security Best Practices

When developing real applications, follow these rules:

  1. Always use HTTPS in production.

  2. Validate input on the PHP server, even if Android also validates it.

  3. Use PDO prepared statements to prevent SQL injection.

  4. Never expose database credentials inside the Android application.

  5. Do not trust user input received from a mobile application.

  6. Avoid returning database passwords, SQL queries or internal server errors to users.

  7. Implement proper authentication and authorization for protected APIs.

  8. Store sensitive information securely.

  9. Apply appropriate request limits and server-side validation.

Remember: Android-side validation improves the user experience, but server-side validation is essential for data security.

18. Conclusion

In this tutorial, we successfully connected an Android application to a PHP and MySQL backend.

We created a Student Registration App that sends student details from Android to a PHP API and stores them in a MySQL database.

We learned:

  • Android to PHP communication.

  • HTTP POST requests.

  • JSON data creation and parsing.

  • PHP API development.

  • MySQL database connection using PDO.

  • Inserting records into MySQL.

  • Reading server responses in Android.

  • Testing APIs using XAMPP.

  • Handling common connection errors.

  • Basic API security practices.

This is an important foundation for building real-world Android applications with online databases.

19. Frequently Asked Questions

Q1. Can an Android application connect directly to MySQL?

Android applications should normally communicate with a backend API rather than connect directly to MySQL. The backend controls database access and validation.

Q2. Why do we use PHP between Android and MySQL?

PHP acts as the backend layer. It receives Android requests, validates data and executes database operations.

Q3. What is an HTTP POST request?

An HTTP POST request sends information to a server, commonly to create a new record.

Q4. Why do we use JSON?

JSON provides a structured and lightweight format for exchanging data between Android and PHP.

Q5. What is PDO in PHP?

PDO stands for PHP Data Objects. It provides a consistent interface for connecting to databases and executing queries.

Q6. Why do we use prepared statements?

Prepared statements safely pass user values into SQL queries and help prevent SQL injection.

Q7. Can the same PHP API work with multiple Android applications?

Yes. A properly designed backend API can serve multiple Android applications and other clients that follow the same API format.

←
Post 27 of 40
→