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.
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….
[…] Mysql Connection PDO […]
Cool. Your blog looks great, and I’m glad i’ve found something here worth adding to my favorites.
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!