How to Connect to a MySQL Database with PHP PDO

When building a web application with PHP, connecting to a database is a step you almost always need. PHP offers several ways to connect to MySQL, but the most recommended approach...

How to Connect to a MySQL Database with PHP PDO

When building a web application with PHP, connecting to a database is a step you almost always need. PHP offers several ways to connect to MySQL, but the most recommended approach today is using PDO (PHP Data Objects). PDO provides a consistent interface across different database types, supports prepared statements for security, and is easier to manage than the old mysql_* functions, which are no longer supported.

Why Use PDO?

Before writing any code, it helps to understand the advantages of PDO over the old approach:

  • Database agnostic — the same code can be used for MySQL, PostgreSQL, SQLite, and more with minimal changes.
  • Built-in prepared statements — protect against SQL Injection automatically.
  • Good error handling — it can throw exceptions, making debugging easy.
  • Actively supported — continuously developed and recommended in modern PHP.

Prerequisites

Make sure the PDO and PDO_MySQL extensions are enabled in your PHP installation. Check by creating a phpinfo.php file and looking for the PDO section, or run the following command in your terminal:

php -m | grep -i pdo

The result should show PDO and pdo_mysql. If they are not enabled, enable them in your php.ini file by removing the semicolon in front of the extension=pdo_mysql line.

Creating a Basic PDO Connection

Here is the most basic way to create a PDO connection to a MySQL database:

<?php

$host     = 'localhost';
$dbname   = 'database_name';
$username = 'root';
$password = '';
$charset  = 'utf8mb4';

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

try {
    $pdo = new PDO($dsn, $username, $password);
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

The DSN (Data Source Name) is a string that tells PDO which database type is used, the server address, the database name, and the charset. The try-catch block is used to catch connection errors without exposing the raw error message to the user.

Setting the PDO Error Mode

By default, PDO does not throw an exception when a query error occurs. You need to set the ERRMODE_EXCEPTION attribute so errors are easy to detect during development:

<?php

$dsn = "mysql:host=localhost;dbname=database_name;charset=utf8mb4";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, 'root', '', $options);
    echo "Connected successfully with full configuration!";
} catch (PDOException $e) {
    // In production, never show the error message to the user
    error_log($e->getMessage());
    die("A database connection error occurred.");
}

The three options set above are highly recommended:

  • ERRMODE_EXCEPTION — throw an exception on error, making debugging easier.
  • FETCH_ASSOC — query results are returned as an associative array (easier to read).
  • EMULATE_PREPARES = false — use native MySQL prepared statements, which are safer.

Moving the Connection to a Separate File

A best practice is to keep the connection configuration in a separate file so it is easy to manage and you do not have to rewrite it every time:

<?php
// File: config/database.php

function getConnection(): PDO
{
    static $pdo = null;

    if ($pdo === null) {
        $host   = $_ENV['DB_HOST']   ?? 'localhost';
        $db     = $_ENV['DB_NAME']   ?? 'database_name';
        $user   = $_ENV['DB_USER']   ?? 'root';
        $pass   = $_ENV['DB_PASS']   ?? '';
        $charset = 'utf8mb4';

        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        $pdo = new PDO($dsn, $user, $pass, $options);
    }

    return $pdo;
}

Then, in another file, simply call the function:

<?php
// File: index.php

require_once 'config/database.php';

$pdo = getConnection();

$stmt = $pdo->query("SELECT * FROM users LIMIT 5");
$users = $stmt->fetchAll();

foreach ($users as $user) {
    echo $user['name'] . "<br>";
}

Additional Security Tips

  • Store database credentials in a .env file or environment variables, not directly in the code.
  • Make sure the configuration file cannot be accessed directly through the browser (keep it outside the public folder).
  • Always use prepared statements when accepting user input — this will be covered further in the CRUD article.
  • Use the utf8mb4 charset to support emoji and special characters.

Conclusion

PDO is the best way to connect to a MySQL database in modern PHP. By using PDO, you get better security through prepared statements, clean error handling, and code that is easier to maintain. Always be sure to set the error mode and fetch mode options, and store your credentials in a safe place. Once the connection is established, you are ready to perform CRUD operations on the database.

php pdo koneksi database mysql php php data objects pdo mysql php native database koneksi mysql php
Share this article
Back to Blog
🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →