In this source code example, you’ll learn step by step how to connect to a MySQL database from PHP using PDO.
Prerequisites
Before connecting to a MySQL database server, you need to have:
- A MySQL database server, a database (create database test_db), and an account that has access to the database.
- PDO MySQL driver enabled in the php.ini file
PHP Connect to MySQL with PDO
The following index.php script illustrates how to connect to the test_db database on the MySQL database server with the root account:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$host= "localhost";
$username= "root";
$password = "";
$db_name = "test_db";
try{
$conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Print host information
echo "Connect Successfully. Host info: " .
$conn->getAttribute(constant("PDO::ATTR_CONNECTION_STATUS"));
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
PDO_MYSQL is a driver that implements the PDO interface. PDO uses the PDO_MYSQL driver to connect to a MySQL database.
PDO uses a data source name (DSN) that contains the following information:
- The database server host
- The database name
- The user
- The password
- and other parameters such as character sets, etc.
Create an instance of the PDO class to make a connection to a MySQL database:
$conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
Comments
Post a Comment