PHP MySQL Connection using PDO

PHP PDO connection to MySQL database

Before a PHP application can read or modify MySQL data, it must establish a database connection. PDO creates the connection using a DSN together with the database username, password and optional connection settings.

PHP script
    |
    v
PDO connection
    |
    +-- DSN
    +-- Username
    +-- Password
    +-- PDO options
    |
    v
MySQL database

In the Plus2net PDO tutorials, the connection object is stored in the variable $dbo. Once $dbo is available, the same connection can be used for prepared statements, SELECT queries, INSERT, UPDATE, DELETE and transactions.

PDO MySQL Requirements Top ↑

The PHP installation must have the PDO MySQL driver available before a MySQL PDO connection can be created.

if(in_array('mysql',PDO::getAvailableDrivers(),true)){
    echo 'PDO MySQL driver is available.';
}else{
    echo 'PDO MySQL driver is not available.';
}

If MySQL is not listed, see the PDO installation tutorial and php.ini configuration tutorial.

Understanding the MySQL PDO DSN Top ↑

DSN stands for Data Source Name. For a MySQL connection it identifies the database driver, server, database name and character set.

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

The parts are:

mysql:
Use the PDO MySQL driver.
host=localhost
MySQL server hostname or IP address.
dbname=pdo
Database to use after connecting.
charset=utf8mb4
Character set used by the MySQL connection.

The server can also be identified by an IP address when required.

Create a Common config.php PDO Connection File Top ↑

Instead of repeating the connection code on every PHP page, keep it in one common file such as config.php.

When the server, database name, username or password changes, only the common configuration needs to be updated.

<?php
$host_name='localhost';
$database='pdo';
$username='root';
$password='';

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

$options=[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false
];

try{
    $dbo=new PDO(
        $dsn,
        $username,
        $password,
        $options
    );
}catch(PDOException $e){
    error_log($e->getMessage());
    exit('Database connection failed.');
}
The empty username/password values shown in many local development setups should be replaced with the actual credentials used by your MySQL server.

Recommended PDO Connection Options Top ↑

The example passes several PDO attributes while the connection is created.

PDO::ATTR_ERRMODE Top ↑

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

Database errors are reported as exceptions so they can be handled with try and catch.

PDO::ATTR_DEFAULT_FETCH_MODE Top ↑

PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC

Rows fetched without specifying another mode are returned as associative arrays.

PDO::ATTR_EMULATE_PREPARES Top ↑

PDO::ATTR_EMULATE_PREPARES => false

For PDO MySQL, this requests native prepared statements where supported instead of PDO emulating the prepared statement in PHP.

Use config.php from Another PHP File Top ↑

Once the connection code is stored in config.php, include it wherever the database connection is required.

require 'config.php';

After this line, the page can use the `$dbo` PDO object.

require 'config.php';

$stmt=$dbo->prepare(
    "SELECT id,name,class
     FROM student
     WHERE id=:id"
);

$stmt->bindValue(
    ':id',
    5,
    PDO::PARAM_INT
);

$stmt->execute();

$row=$stmt->fetch();

Handle PDO Connection Errors Safely Top ↑

The older approach of displaying the complete connection exception directly in the browser can reveal technical database details.

Instead, log the detailed error and display a short message:

try{
    $dbo=new PDO(
        $dsn,
        $username,
        $password,
        $options
    );
}catch(PDOException $e){
    error_log($e->getMessage());
    exit('Database connection failed.');
}

Detailed exception messages remain available in the server log without exposing them to website visitors.

PDO Error Handling

Test a PDO MySQL Connection Top ↑

During local development, a simple test file can confirm that config.php creates the `$dbo` object.

<?php
require 'config.php';

if($dbo instanceof PDO){
    echo 'PDO connection created successfully.';
}

Remove development-only connection messages when they are no longer required.

Connect PHP to SQLite using PDO Top ↑

PDO uses a different DSN when connecting to SQLite. No MySQL hostname, username or password is required for a normal SQLite database file.

$dbo=new PDO(
    'sqlite:'.__DIR__.'/my_student.db'
);

$dbo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);
PDO SQLite Connection

Connect PHP to PostgreSQL using PDO Top ↑

The PDO programming interface is similar, but the DSN changes to use the PostgreSQL driver.

$dsn='pgsql:host=localhost;port=5432;dbname=testdb';

$options=[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];

try{
    $dbo=new PDO(
        $dsn,
        'username',
        'password',
        $options
    );
}catch(PDOException $e){
    error_log($e->getMessage());
    exit('Database connection failed.');
}
PDO provides a common PHP interface, but changing database systems can still require changes to the DSN, SQL syntax, data types and database-specific features.

Set a PDO Connection Timeout Top ↑

PDO::ATTR_TIMEOUT can be supplied as a driver option where the PDO driver supports it.

$options=[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_TIMEOUT => 5
];

$dbo=new PDO(
    $dsn,
    $username,
    $password,
    $options
);
Timeout support and exact behavior can vary between PDO drivers. Do not assume that the same timeout option behaves identically with every database system.

Persistent PDO Connections Top ↑

PDO can request a persistent connection by setting PDO::ATTR_PERSISTENT to true.

$options=[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_PERSISTENT => true
];

$dbo=new PDO(
    $dsn,
    $username,
    $password,
    $options
);

A persistent connection may allow PHP to reuse an existing database connection rather than creating a new one for every request.

Persistent connections are optional and should not automatically be enabled for every project. Their usefulness depends on the PHP server model, database configuration and application workload.

Connect PDO to a Remote or Cloud MySQL Database Top ↑

The PDO code is similar when MySQL runs on another server. Replace localhost with the hostname or IP address supplied for the database server.

$host_name='YOUR_DATABASE_HOST';
$database='my_tutorial';
$username='YOUR_DATABASE_USER';
$password='YOUR_DATABASE_PASSWORD';

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

$options=[
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false
];

try{
    $dbo=new PDO(
        $dsn,
        $username,
        $password,
        $options
    );
}catch(PDOException $e){
    error_log($e->getMessage());
    exit('Database connection failed.');
}

$sql="SELECT id,name
      FROM student
      ORDER BY id
      LIMIT 10";

$stmt=$dbo->query($sql);

foreach($stmt as $row){
    echo htmlspecialchars(
        (string)$row['name'],
        ENT_QUOTES,
        'UTF-8'
    ).'<br>';
}

The remote database server must also allow connections from the PHP server. Cloud database platforms can require additional network, firewall or connection configuration.

Managing MySQL Database at Google Cloud

PDO Connection Video Tutorials Top ↑

PHP PDO installation, driver support and MySQL connection string

Using a common config.php file for PDO database connection details

Podcast on MySQL database management using PHP PDO

PDO Connection Security Tips Top ↑

  • Do not display raw PDO connection exceptions to website visitors.
  • Use a dedicated database account with the permissions required by the application.
  • Do not place real passwords inside tutorial examples or public source repositories.
  • Keep connection settings in one controlled configuration file instead of repeating credentials throughout the application.
  • Use prepared statements when SQL queries contain variable or user-supplied values.
  • For production systems, follow the connection and network security requirements of the database hosting provider.
PDO Tutorial PDO Installation PDO Records PDO Fetch

PDO Error Handling PDO Prepared Statements and Injection

Download the complete sample PDO project from the main PHP PDO tutorial.

Frequently Asked Questions Top ↑

Q1: How do I connect PHP to MySQL using PDO?

Create a MySQL DSN containing the host, database name and character set, then create a PDO object using the DSN, database username, password and connection options.

Q2: What is a PDO DSN?

DSN stands for Data Source Name. It tells PDO which database driver to use and provides connection information such as the host and database name.

Q3: Why should I include charset=utf8mb4 in a MySQL PDO connection?

It sets the character set used by the MySQL connection to utf8mb4 so the connection handles the corresponding Unicode character range.

Q4: Why keep the PDO connection in config.php?

A common config.php file avoids repeating database connection settings across many PHP pages and makes connection changes easier to maintain.

Q5: How should PDO connection errors be handled?

Catch PDOException, log the detailed technical message on the server and display a short connection-failed message instead of exposing database information to visitors.

Q6: Can PDO connect to databases other than MySQL?

Yes. PDO can use different database drivers. For example, SQLite and PostgreSQL use different DSN formats while keeping a similar PDO programming interface.

Q7: Should I always use persistent PDO connections?

No. Persistent connections are optional. Whether they are useful depends on the PHP server model, database configuration and application workload.


PDO PDO Records PDO Fetch


Subscribe to our YouTube Channel here



plus2net.com







02-10-2021

cant we connect to a phpmyadmin sql database?




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer