MySql Database Connection with PDO

  • Avinash
  • 4
  • Aug 19, 2010
  • Tutorial

In previous post I have introduced some basic introduction about the PDO ( PHP DATA OBJECT ).

In this post I will describe how to establish connection with mysql database using PDO.

To make connection with database you should have following details.

  • Database Host
  • Database User Name
  • Database Password
  • Database Name

To make connection with mysql database below code is used.

<?php

   $user="db user name";
   $pass="?db password";
   $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

?>

Above code will connect to the database if all details are correct. This code will return the resource id if database connected successfully. Here $dbh stands for Database Handler.

Now what happen if the given details are incorrect? So for this case PDO has developed their own exception class. This class called PDOException.

Using this class you can handle the error as you want. Below is the example for that.

getMessage() . "
"; die(); } ?>
<?php
    try
   {
         $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   }
   catch (PDOException $e)
   {
       print "Error!: " . $e->getMessage() . "<br/>";
       die();
   }
?>

Now closing the connection in PDO is so easy. Just declare the database handler to null will close the connection.

<?php
      $dbh=null;
?>

In next tutorial I will explain how to fetch data using PDO and Prepare Statement in PDO.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by:

  • Pingback: pligg.com

  • Pingback: prepare statements with PDO | Xpert Developer

  • Yong Cesaire

    Cool. Your blog looks great, and I’m glad i’ve found something here worth adding to my favorites.

  • http://dochoi.otopro.net do choi o to

    Hi there! I could have sworn I’ve been to this website before but after browsing through many of the articles I realized it’s new to me. Regardless, I’m definitely happy I found it and I’ll be bookmarking it and checking back regularly!