Lesson 58 of 60 – PHP MySQL API for React Native
97%

PHP MySQL API for React Native

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.

Note: React Native does not normally connect directly to MySQL. A PHP API acts as the middle layer between the mobile application and the MySQL database.

1. What is a PHP MySQL API?

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

2. Why Use PHP with React Native?

PHP can provide the backend services required by a mobile application.

  • User registration
  • User login
  • Student management
  • Course management
  • Fee management
  • Product management
  • Data retrieval
  • Data insertion and updates

3. Why Use MySQL?

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

4. React Native Does Not Directly Connect to MySQL

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.

5. Creating a MySQL Database

First, create a database for the application.

CREATE DATABASE mobile_app;

Then select the database:

USE mobile_app;

6. Creating a MySQL Table

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

);

7. Connecting PHP to MySQL

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");

}

8. Creating a PHP API Folder

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.

9. Setting JSON Response Headers

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.

10. Returning JSON from PHP

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.

11. Fetching Students from MySQL

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);

12. Calling the PHP API with Fetch

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);

13. Displaying API 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);
}

14. Displaying Students with FlatList

<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.

15. Sending POST Data to PHP

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"
        })
    }
);

16. Reading JSON Input in PHP

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"] ?? "";

17. Inserting Data into MySQL

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.

18. Returning an Insert Response

echo json_encode([
    "success" => true,
    "message" => "Student added successfully",
    "id" => $pdo->lastInsertId()
]);

React Native can inspect the response and display an appropriate message.

19. Updating MySQL Data

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
]);

20. Deleting MySQL Data

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.

21. PHP API for Login

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.

22. Password Verification in PHP

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

}

23. Authentication API Response

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"]
    ]
]);

24. PHP API with Axios

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
    }
);

25. Handling API Errors

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"
    );

}

26. Common PHP MySQL API Mistakes

  • Connecting React Native directly to MySQL.
  • Using SQL queries without prepared statements for user input.
  • Returning invalid JSON.
  • Forgetting the JSON response header.
  • Not validating API input.
  • Returning database errors directly to users.
  • Storing passwords as plain text.
  • Using HTTP instead of HTTPS in production.
  • Not authenticating protected API endpoints.
  • Hard-coding database credentials in publicly accessible files.

27. Complete PHP Students API

<?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.

28. PHP MySQL API Best Practices

  • Use PDO or another secure database access layer.
  • Use prepared statements for user-supplied values.
  • Return valid JSON responses.
  • Use appropriate HTTP status codes.
  • Validate all incoming data.
  • Use HTTPS in production.
  • Never expose database credentials to the mobile application.
  • Hash passwords securely.
  • Authenticate protected endpoints.
  • Keep database and API code organized.
  • Do not expose unnecessary database information.
  • Handle server and database errors safely.

29. Important PHP MySQL API Concepts

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

30. Complete React Native + PHP + MySQL Workflow

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.

📌 Key Points

  • React Native normally communicates with MySQL through a backend API.
  • PHP can be used to build the backend API.
  • MySQL can store application data.
  • Fetch and Axios can send HTTP requests from React Native.
  • JSON is commonly used to transfer data between the app and API.
  • PDO can connect PHP to MySQL.
  • Prepared statements should be used for database operations involving user input.
  • PHP can perform SELECT, INSERT, UPDATE, and DELETE operations.
  • Passwords should be securely hashed.
  • Authentication should be handled by the backend.
  • Use HTTPS for production API communication.
  • API errors should be handled on both the server and mobile application.

🧠 Quick Quiz

Question: How should a React Native application normally communicate with a MySQL database?