Tutorial

MySql Database Connection with PDO

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.

[cc lang=”php”]

[/cc]

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.

[cc lang=”php”]
getMessage() . “
“;
die();
}
?>
[/cc]

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

[cc lang=”php”]

[/cc]

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

Shares:
  • pligg.com
    August 26, 2010 at 7:33 pm

    MySql Database Connection with PDO | Xpert Developer…

    PDO (PHP Data Object) is the lightweight and consistent interface for accessing the multiple databases (even of different types) through PHP. PDO uses its own exception class to handle the errors….

    Reply
  • prepare statements with PDO | Xpert Developer
    September 13, 2010 at 12:37 pm

    […] Mysql Connection PDO […]

    Reply
  • Yong Cesaire
    Yong Cesaire
    September 21, 2010 at 2:44 am

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

    Reply
  • do choi o to
    February 29, 2012 at 9:49 pm

    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!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *