PHP: Connecting PHP to MySQL with PDO
This documentation is part of the Establishing a MySQL Connection guide. You can view the complete guide here: Learn how to connect to MySQL from PHP using MySQLi and PDO.
👋 Welcome to the Stackhero documentation!
Stackhero offers managed PHP hosting designed for fast, reliable deployments:
- Deploy your PHP application to production in seconds with a simple
git push.- Use your own domain, with automatic HTTPS certificates set up for you. No manual intervention required.
- Take advantage of automatic backups, one-click updates, and straightforward, predictable pricing. Stackhero manages these aspects so you can focus on your code.
- Enjoy robust performance and security on a private, dedicated infrastructure tailored specifically for your applications.
Streamline your workflow and save time. Getting started with Stackhero's PHP hosting for Laravel and Symfony only takes a few minutes.
PDO provides a flexible way to connect PHP to MySQL. The example below illustrates how to use PDO to establish a connection. It also covers potential SSL certificate issues that may occur if your system does not have access to CA certificates.
<?php
$hostname = '<XXXXXX>.stackhero-network.com';
$user = 'root';
$password = '<yourPassword>';
$database = 'root'; // In production environments, consider creating a dedicated database and user
$dsn = "mysql:host=$hostname;dbname=$database";
$options = array(
// If you encounter an error such as "Uncaught PDOException: PDO::__construct(): SSL operation failed with code 1...",
// it may be because the /etc/ssl/certs/ directory does not contain CA certificates
PDO::MYSQL_ATTR_SSL_CAPATH => '/etc/ssl/certs/',
// PDO::MYSQL_ATTR_SSL_CA => 'isrgrootx1.pem',
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true,
);
$pdo = new PDO($dsn, $user, $password, $options);
$stm = $pdo->query('SELECT VERSION()');
$version = $stm->fetch();
echo 'You are connected to a database running version ' . $version[0] . "\n";
?>
Resolving the error "SSL operation failed with code 1"
If you encounter an error such as Uncaught PDOException: PDO::__construct(): SSL operation failed with code 1. OpenSSL Error messages: error:0A000086:SSL routines::certificate verify failed, it is likely that your system's /etc/ssl/certs/ directory does not contain the required CA certificates.
If you have access to the system running your PHP code, you can install the certificates as follows:
- On Ubuntu/Debian, run
sudo apt-get install ca-certificates - On Alpine Linux, run
apk add ca-certificates
If you do not have the ability to install these certificates directly on your system, you can install the certificate manually:
- Download the certificate to your computer: https://letsencrypt.org/certs/isrgrootx1.pem
- Add the
isrgrootx1.pemfile to your PHP project files. - Comment out the line
PDO::MYSQL_ATTR_SSL_CAPATH => '/etc/ssl/certs/' - Uncomment the line
PDO::MYSQL_ATTR_SSL_CA => 'isrgrootx1.pem'