Site Loader
Get a Quote

PDO MySQL Connection in PHP 


PDO MySQL Connection in PHP: –  Hi readers today we came up with the topic “ how to create a PDO MySQL Connection in PHP “. Here we have explained the details and then full source code with the result which makes you more understanding of how we create a new PDO MySQL Connection in PHP Script.

“PDO stands for PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”

it supports oops concept but not procedural and its very fast and secure way now MySQL has been an old way.

 How to create a PDO MySQL Connection in PHP 


To start working with database one must first establish a connection by creating an instance of PDO base class.

 //create a new instance of PDO base class
 $conn=new PDO("mysql:host=$host;dbname=pdo",$username,$password);

Here host is a localhost by default, a username is the specified username, by default root and password can be any specified password but by default, it is null or empty(“).

using these three parameters in PDO base class one can establish a connection and if there is any error in establishing a connection then it is handled by catch block by displaying the error message

Below is the code snippet to check the condition :

  //check the condition
 //set the PDO error mode to exception
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Close the connection


An established connection is closed by clearing the garbage collection and clear the resources or memory while used during connection.

//close the connection
 $conn=null;

Full source Code:

<?php
$host="localhost";
$username="root";
$password="";
//try block
try
{
 //create a new instance of PDO base class
 $conn=new PDO("mysql:host=$host;dbname=pdo",$username,$password);

 //set the PDO error mode to exception
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 //display message
 echo "connected successfully";
 }
 //catch block to handle exception if any
 catch(PDOException $e)
 {
 echo "connection failed". $e->getMessage();
 }

 ?>


ScreenShot View of PDO  Connection in PHP:

       

PDO MySQL Connection in PHP
PDO MySQL Connection in PHP

I hopes you would like this tutorial on how to create PDO MySQL Connection in PHP !

Post Author: TechieFlair

Leave a Reply

Your email address will not be published.