How to connect database using PDO in PHP

Connect database using PDO in PHP

In this post, you will be learning how to connect database using pdo in php.


1. MySql Database Server.

2. PDO should be enabled, but PDO is enabled by default as of php 5.1. 0 

Give the Connection to MySQL Database using PDO as given below:

$servername = "localhost";
$username = "username";
$password = "password";
$database = "database_name";

try {

    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception
    echo "Connected Successfully";
} catch(PDOException $e) {

    echo "Connection Failed" .$e->getMessage();


Thank you.