Lesson 52 of 158 – PHP PDO Connection
52%

PHP PDO Connection

PDO stands for PHP Data Objects. It provides a consistent way for PHP applications to connect to databases and execute SQL queries. In our REST API project, we will use PDO to connect PHP with the student_api MySQL database.

Note: PDO helps us create a reusable and secure database connection that can be used by our REST API files.

1. What is PDO?

PDO means PHP Data Objects. It is a PHP extension used to work with databases.

PDO can be used to connect PHP with MySQL and other supported database systems.

PHP
 ↓
PDO
 ↓
MySQL

2. Why Use PDO?

PDO provides a standard interface for connecting to databases and executing SQL statements.

Some benefits include:

  • Reusable database connection
  • Prepared statements
  • Exception handling
  • Cleaner database code
  • Better security when used correctly

3. PDO and MySQL

Our REST API uses MySQL as the database and PDO as the PHP database access interface.

React Native
      ↓
PHP REST API
      ↓
PDO
      ↓
MySQL
      ↓
student_api

4. Database Information

Before creating a PDO connection, we need the database connection details.

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

These values are typical for a local XAMPP development environment.

5. Host Name

The host identifies the server where MySQL is running.

$host = "localhost";

When MySQL is running on the same computer as PHP, localhost is commonly used.

6. Database Name

The database name tells PDO which MySQL database should be used.

$dbname = "student_api";

This is the database we created in the previous lessons.

7. MySQL Username

The username is required to authenticate with the MySQL server.

$username = "root";

The default local XAMPP MySQL username is commonly root. Production servers usually use a dedicated database user.

8. MySQL Password

The password is used along with the MySQL username.

$password = "";

In some local development environments the root account may have an empty password. Never assume this configuration is appropriate for production.

9. Create the DSN

DSN stands for Data Source Name. It contains information about the database connection.

$dsn = "mysql:host=localhost;dbname=student_api";

The DSN tells PDO that we are connecting to MySQL on localhost and using the student_api database.

10. Add Character Encoding

We can specify UTF-8 character encoding in the DSN.

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

Using utf8mb4 provides broad Unicode support.

11. Create PDO Object

The PDO object can be created by passing the DSN, username, and password.

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

The variable $pdo will represent the database connection.

12. Basic PDO Connection

A simple PDO connection can look like this:

<?php

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

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

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

?>

13. What Happens During Connection?

When the PDO object is created, PHP attempts to connect to the MySQL server.

PHP
 ↓
PDO Connection
 ↓
MySQL Server
 ↓
student_api Database

If the connection is successful, PHP can execute database queries.

14. Try and Catch

Database connections can fail. We can use try and catch to handle connection exceptions.

try {

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

} catch (PDOException $e) {

    echo "Database connection failed.";

}

15. PDOException

PDOException is used to catch PDO-related exceptions.

catch (PDOException $e) {

    echo "Database connection failed.";

}

This allows the application to handle database connection problems.

16. Exception Mode

We can configure PDO to throw exceptions when database errors occur.

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

This makes database errors easier to detect and handle.

17. Complete Connection Code

<?php

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

try {

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

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

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

} catch (PDOException $e) {

    die("Database connection failed.");

}

?>

18. Connection File

It is better to keep the database connection in a separate file instead of writing the connection code in every API file.

For example:

config/
    database.php

The API files can include this file whenever a database connection is required.

19. database.php

A reusable database connection file can contain:

<?php

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

try {

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

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

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

} catch (PDOException $e) {

    die("Database connection failed.");

}

20. Include the Connection File

An API file can include the database connection file.

require_once "config/database.php";

After including the file, the $pdo connection can be used by the API.

21. PDO and SQL Queries

Once the PDO connection is available, PHP can execute SQL queries.

$stmt = $pdo->query(
    "SELECT * FROM students"
);

The query retrieves records from the students table.

22. PDO Prepared Statements

PDO supports prepared statements. Prepared statements are important when working with values supplied by users or mobile applications.

$stmt = $pdo->prepare(
    "SELECT * FROM students WHERE id = ?"
);

The value can then be supplied separately.

23. Execute a Prepared Statement

After preparing a statement, values can be supplied using execute().

$stmt = $pdo->prepare(
    "SELECT * FROM students WHERE id = ?"
);

$stmt->execute([$student_id]);

This separates the SQL statement from the supplied value.

24. PDO in REST API

PDO becomes the database layer between PHP and MySQL in our REST API.

React Native
      ↓
HTTP Request
      ↓
PHP REST API
      ↓
PDO
      ↓
MySQL
      ↓
JSON Response
      ↓
React Native

25. Common PDO Connection Errors

  • MySQL server is not running
  • Incorrect database name
  • Incorrect username
  • Incorrect password
  • Incorrect host
  • PDO MySQL driver is unavailable
  • Database does not exist

Check the connection settings when PDO cannot connect to MySQL.

26. Test the PDO Connection

For learning purposes, you can test whether the connection was successful.

try {

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

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

    echo "Database connected successfully.";

} catch (PDOException $e) {

    echo "Database connection failed.";

}

27. Recommended Project Structure

rest_api/
│
├── config/
│   └── database.php
│
├── api/
│   ├── students.php
│   └── users.php
│
└── index.php

The exact structure can grow as more API features are added.

28. Keep Credentials Secure

Database credentials should not be exposed to the mobile application.

React Native
     ↓
Public API
     ↓
PHP Server
     ↓
Database Credentials
     ↓
MySQL

The database username and password should remain on the server.

29. Final PDO Connection Flow

$host
   ↓
$dbname
   ↓
$username
   ↓
$password
   ↓
$dsn
   ↓
new PDO()
   ↓
$pdo
   ↓
SQL Queries

This connection will be reused by the PHP REST API files.

30. PHP PDO Connection Summary

PDO provides a clean way for PHP to connect with MySQL. In our REST API project, we use PDO to connect to the student_api database. The connection can be placed in a reusable database.php file and included in API files whenever database access is required.

PHP
 ↓
PDO
 ↓
student_api
 ↓
students
 ↓
REST API

📌 Key Points

  • PDO stands for PHP Data Objects.
  • PDO is used to connect PHP with databases.
  • Our project uses MySQL.
  • The database name is student_api.
  • The DSN contains the database connection information.
  • new PDO() creates the PDO connection.
  • PDOException can be used to handle connection errors.
  • PDO::ERRMODE_EXCEPTION enables exception-based error handling.
  • A reusable connection can be stored in database.php.
  • API files can include the connection using require_once.
  • PDO supports prepared statements.
  • Database credentials should remain on the server.

🧠 Quick Quiz

Question: What does PDO stand for in PHP?