React Native applications commonly communicate with a backend server through APIs. PHP can be used to create the backend API, while MySQL can be used to store application data.
In this lesson, we will learn how a React Native application can send requests to a PHP API and how the PHP API can read and write data in a MySQL database.
A PHP MySQL API is a backend application that receives requests from a client application, communicates with MySQL, and returns a response.
React Native
↓
HTTP Request
↓
PHP API
↓
MySQL
↓
PHP API
↓
JSON Response
↓
React Native
PHP can provide the backend services required by a mobile application.
MySQL is a relational database system that can store structured application data.
For example, an education application could have tables such as:
students
courses
payments
attendance
The mobile application should not normally connect directly to a MySQL database.
Instead, the application sends HTTP requests to a backend API.
React Native
↓
PHP API
↓
MySQL Database
This separation allows the backend to control database access and application rules.
First, create a database for the application.
CREATE DATABASE mobile_app;
Then select the database:
USE mobile_app;
For example, we can create a students table.
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL,
course VARCHAR(100) NOT NULL
);
PHP can use PDO to connect to MySQL.
<?php
$host = "localhost";
$dbname = "mobile_app";
$username = "root";
$password = "";
try {
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname",
$username,
$password
);
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
} catch (PDOException $e) {
die("Database connection failed");
}
A simple PHP API project can have separate files for different operations.
api/
│
├── db.php
├── students.php
├── login.php
├── register.php
└── add_student.php
Keeping API files organized makes the backend easier to maintain.
A PHP API commonly returns JSON data to the React Native application.
<?php
header(
"Content-Type: application/json"
);
This tells the client that the response contains JSON data.
PHP can use json_encode() to convert PHP data into JSON.
$data = [
"id" => 1,
"name" => "Rahul",
"course" => "React Native"
];
echo json_encode($data);
React Native can then convert the response into a JavaScript object.
PHP can execute a SELECT query and return the results.
<?php
require "db.php";
header(
"Content-Type: application/json"
);
$stmt = $pdo->query(
"SELECT id, name, email, course
FROM students"
);
$students =
$stmt->fetchAll(
PDO::FETCH_ASSOC
);
echo json_encode($students);
React Native can use the Fetch API to request data from the PHP server.
const response = await fetch(
"https://example.com/api/students.php"
);
const data =
await response.json();
console.log(data);
The returned data can be stored in React state.
const [students, setStudents] =
useState([]);
async function loadStudents() {
const response = await fetch(
"https://example.com/api/students.php"
);
const data =
await response.json();
setStudents(data);
}
<FlatList
data={students}
keyExtractor={
item => item.id.toString()
}
renderItem={({ item }) => (
<Text>
{item.name}
</Text>
)}
/>
FlatList is useful for displaying a large list of API records efficiently.
React Native can send data to PHP using an HTTP POST request.
const response = await fetch(
"https://example.com/api/add_student.php",
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name: "Amit",
email: "amit@example.com",
course: "React Native"
})
}
);
When React Native sends JSON, PHP can read the request body using
php://input.
$input =
json_decode(
file_get_contents(
"php://input"
),
true
);
$name =
$input["name"] ?? "";
$email =
$input["email"] ?? "";
$course =
$input["course"] ?? "";
Use a prepared statement when inserting values received from a client.
$stmt = $pdo->prepare(
"INSERT INTO students
(name, email, course)
VALUES (?, ?, ?)"
);
$stmt->execute([
$name,
$email,
$course
]);
Prepared statements help protect database queries from SQL injection.
echo json_encode([
"success" => true,
"message" => "Student added successfully",
"id" => $pdo->lastInsertId()
]);
React Native can inspect the response and display an appropriate message.
An API can also update an existing record.
$stmt = $pdo->prepare(
"UPDATE students
SET name = ?, email = ?, course = ?
WHERE id = ?"
);
$stmt->execute([
$name,
$email,
$course,
$id
]);
A DELETE API can remove a specific record.
$stmt = $pdo->prepare(
"DELETE FROM students
WHERE id = ?"
);
$stmt->execute([
$id
]);
The API should verify that the request is authorized before deleting important application data.
A login API can receive an email and password and check the user account in MySQL.
$input =
json_decode(
file_get_contents(
"php://input"
),
true
);
$email =
$input["email"] ?? "";
$password =
$input["password"] ?? "";
The backend should then verify the credentials using a secure authentication design.
Passwords should be stored as secure password hashes rather than plain text.
PHP provides password_hash() for creating password hashes
and password_verify() for checking a password.
$hash = password_hash(
$password,
PASSWORD_DEFAULT
);
During login:
if (
password_verify(
$password,
$user["password"]
)
) {
// Login successful
}
After successful authentication, the API can return information required by the mobile application according to the chosen authentication architecture.
echo json_encode([
"success" => true,
"message" => "Login successful",
"user" => [
"id" => $user["id"],
"name" => $user["name"],
"email" => $user["email"]
]
]);
Axios can also communicate with PHP APIs.
const response = await axios.get(
"https://example.com/api/students.php"
);
setStudents(
response.data
);
POST requests can be used to send data to PHP.
await axios.post(
"https://example.com/api/add_student.php",
{
name,
email,
course
}
);
Both PHP and React Native should handle errors appropriately.
try {
const response = await fetch(
"https://example.com/api/students.php"
);
if (!response.ok) {
throw new Error(
"API request failed"
);
}
const data =
await response.json();
setStudents(data);
} catch (error) {
setError(
"Unable to load students"
);
}
<?php
require "db.php";
header(
"Content-Type: application/json"
);
try {
$stmt = $pdo->query(
"SELECT
id,
name,
email,
course
FROM students
ORDER BY id DESC"
);
$students =
$stmt->fetchAll(
PDO::FETCH_ASSOC
);
echo json_encode([
"success" => true,
"students" => $students
]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Database error"
]);
}
This example returns a JSON response containing student records.
| Technology | Purpose |
|---|---|
| React Native | Mobile application interface and client logic |
| Fetch / Axios | Sends HTTP requests to the API |
| PHP | Backend API logic |
| MySQL | Stores application data |
| PDO | Provides PHP database access |
| JSON | Transfers structured data between client and server |
| Prepared Statement | Helps safely execute SQL with supplied values |
React Native Application
↓
Fetch / Axios
↓
HTTP Request
↓
PHP API
↓
Validate Data
↓
PDO / SQL
↓
MySQL Database
↓
Query Result
↓
PHP API
↓
JSON Response
↓
React Native
↓
Update UI
This architecture is widely useful for mobile applications that need server-side data. React Native handles the mobile interface, PHP handles the API logic, and MySQL stores persistent application data.
Question: How should a React Native application normally communicate with a MySQL database?