Lesson 49 of 158 – PHP MySQL Connection
49%

PHP MySQL Connection

In our REST API project, PHP needs to communicate with the MySQL database. A database connection allows PHP to send SQL queries to MySQL and receive the required data.

Note: In this project, we will use PHP PDO to connect our REST API with MySQL. PDO will be covered in more detail in the upcoming lesson.

1. Why Connect PHP with MySQL?

Our Student Management API needs a database to store student information. PHP acts as the backend and communicates with MySQL.

React Native
      ↓
PHP REST API
      ↓
MySQL Database

2. What is a Database Connection?

A database connection creates a communication link between the PHP application and the MySQL server.

PHP
 ↓
Database Connection
 ↓
MySQL

After the connection is established, PHP can execute database operations.

3. MySQL Server

MySQL is the database server that will store the data for our REST API.

For example, our database can contain a table named:

students

The table can contain student names, emails, mobile numbers, and courses.

4. Database Information

PHP needs some information to connect to MySQL.

  • Database host
  • Database name
  • Database username
  • Database password

These values depend on your local or production database configuration.

5. Database Host

The database host identifies the computer where MySQL is running.

For a typical local development environment, it may be:

localhost

Another server may use a different hostname or IP address.

6. Database Name

The database name identifies the specific MySQL database used by our application.

For example:

student_api

The database must exist before the application can use its tables.

7. Database Username

PHP needs a MySQL username with permission to access the database.

For a typical local development setup, the username may be:

root

Production servers normally use a dedicated database account.

8. Database Password

PHP may also need the password for the MySQL user.

A local development installation may have an empty password, depending on how MySQL was configured.

$password = "";

Production databases should use strong credentials and should not expose them publicly.

9. Create database.php

Create a file named database.php inside the config folder.

student_api/
│
└── config/
    └── database.php

This file will contain our database connection code.

10. Basic PDO Connection

A basic PDO connection can be created like this:

<?php

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

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

This creates a PDO object that can communicate with MySQL.

11. Understanding the DSN

The first argument passed to PDO is called the Data Source Name (DSN).

mysql:host=localhost;dbname=student_api

It tells PDO which database driver, host, and database should be used.

12. MySQL PDO Driver

The DSN begins with:

mysql:

This tells PDO that the application is connecting to a MySQL database.

13. Host in DSN

The host can be specified inside the DSN.

mysql:host=localhost

For a local MySQL server, localhost is commonly used.

14. Database Name in DSN

The database name can also be specified in the DSN.

mysql:host=localhost;dbname=student_api

Here, PHP will connect to the student_api database.

15. Charset

It is useful to specify the character set for the database connection.

mysql:host=localhost;dbname=student_api;charset=utf8mb4

Using an appropriate character set helps the application handle a wide range of text correctly.

16. Connection with Charset

<?php

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

$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";

$pdo = new PDO($dsn, $username, $password);

This creates the connection using the MySQL driver and UTF-8 compatible character encoding.

17. Enable PDO Exceptions

PDO can be configured to throw exceptions when database errors occur.

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

Exceptions make database errors easier to detect and handle during development.

18. Complete Basic Connection

<?php

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

$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";

$pdo = new PDO($dsn, $username, $password);

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

19. Handle Connection Errors

A try-catch block can be used to handle connection exceptions.

try {

    $pdo = new PDO(
        $dsn,
        $username,
        $password
    );

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

} catch (PDOException $e) {

    die("Database connection failed.");

}

For production APIs, error responses should be designed carefully so that sensitive database details are not exposed to clients.

20. Include the Connection in API

Our API endpoint can include the database connection file.

require_once '../config/database.php';

After including the file, the API can use the PDO connection.

21. API and Database Flow

Client Request
      ↓
students.php
      ↓
database.php
      ↓
PDO Connection
      ↓
MySQL
      ↓
Query Result
      ↓
JSON Response

This is the basic database communication flow of our REST API.

22. Test the Database Connection

During development, you can temporarily test whether the connection was created successfully.

echo "Database connected successfully";

Do not leave debugging output inside a JSON API response in the final version.

23. Connection File Structure

student_api/
│
├── config/
│   └── database.php
│
└── api/
    └── students.php

The API file can reuse the connection defined in the config folder.

24. Why Reuse One Connection File?

If multiple API files need database access, creating the connection separately in every file can lead to duplicated code.

Instead, keep the connection in one reusable file.

database.php
     ↓
students.php
courses.php
users.php

25. Database Connection Mistakes

  • Incorrect database name
  • Incorrect username
  • Incorrect password
  • Incorrect host
  • MySQL server is not running
  • Incorrect relative path
  • PDO MySQL driver is unavailable

Check these items when a PHP application cannot connect to MySQL.

26. Database Server Must Be Running

Before testing the API locally, make sure the MySQL server is running.

If you are using a local development package such as XAMPP, start the required services before testing the database connection.

27. Connection Security

Database credentials should be protected.

  • Do not expose passwords in API responses.
  • Do not publish database credentials in public repositories.
  • Use appropriate database permissions.
  • Use secure configuration practices in production.
  • Do not display detailed database exceptions to API users.

28. PHP API Database Flow

React Native
      ↓
HTTP Request
      ↓
students.php
      ↓
database.php
      ↓
PDO
      ↓
MySQL
      ↓
Student Data
      ↓
JSON Response
      ↓
React Native

29. Recommended database.php

A simple reusable connection file for our project can look like this:

<?php

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

$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";

try {

    $pdo = new PDO(
        $dsn,
        $username,
        $password
    );

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

} catch (PDOException $e) {

    die("Database connection failed.");

}

30. PHP MySQL Connection Summary

PHP needs a database connection to communicate with MySQL. In our REST API project, we will keep the connection code inside config/database.php and reuse it from our API endpoints. PDO provides the connection mechanism that we will use to execute database operations.

PHP API
   ↓
PDO
   ↓
MySQL
   ↓
Database Tables

📌 Key Points

  • PHP needs a database connection to communicate with MySQL.
  • The database host identifies the MySQL server.
  • The database name identifies the database used by the application.
  • Username and password are used for database authentication.
  • PDO can be used to connect PHP with MySQL.
  • The DSN contains database connection information.
  • charset=utf8mb4 can be used for character encoding.
  • PDO exceptions can help identify database connection errors.
  • The connection can be stored in config/database.php.
  • API files can include the database connection file.
  • Database credentials should be protected.
  • The next lessons will use this connection for actual database operations.

🧠 Quick Quiz

Question: Which PHP technology are we using to connect our REST API with MySQL?