How to Connect to MySQL Database in PHP using PDO
In this tutorial, we are going to see how to connect to MySQL database in PHP using PDO. Before creating a connection to a MySQL database server, you must have:
- A MySQL database server installed on your local system or on a remote server.
- A database on MySQL server.
- MySQL account with a username and password to access the database.
In the example below, we will use:
- The local MySQL database server so that the DSN is localhost.
- A database called “test”.
- Root account with an empty password.
How to Connect to MySQL Database in PHP using PDO
<?php $host = 'localhost'; $dbname = 'test'; $username = 'root'; $password = ''; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); echo "Connected to $dbname on $host successfully."; } catch (PDOException $e) { die("Unable to connect to the database $dbname :" . $e->getMessage()); } ?>
If you have configured everything correctly, you will see the following message:
Connected to test on localhost successfully.
If the MySQL driver is not enabled in php.ini file, you will get the following error message:
Unable to load driver
To check if MySQL PDO driver is enabled, you need to open the php.ini file and uncomment the following line by removing the semicolon (;) at the beginning of the entry:
extension=php_pdo_mysql.dll