PDO – PHP database extension

PDO (PHP Data Objects) is a PHP extension through which we can access and work with databases. Though PDO is similar in many aspects to mySQLi, it is better to work with for the following reasons:

  •  It is better protected against hackers.
  • It is consistent across databases, so it can work with MySQL as well as other types of databases (SQLite, Oracle, PostgreSQL, etc.)
  •  It is object oriented at its core.

In this PDO  tutorial you will find recipes for 4 basic functions that we perform with the database: insertion, selection, update, and deletion. The recipes are intended to work with MySQL, but we can easily switch it with another database.
How to connect with the database through PDO?
It is considered good practice to wrap the database connection within a try-catch block so that, if anything goes wrong, an exception will be thrown. We can customize the error message but, in order to keep things simple, we’ll settle with the error message that PDO provides. In order to connect to the database, we’ll need the database name, username, and password.

// DB credentials.
define('DB_USER','your user name');
define('DB_PASS','your user password');
define('DB_NAME','your database name');
// Establish database connection.
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,
catch (PDOException $e)
exit("Error: " . $e->getMessage());

How to close the database connection?

PHP automatically closes the database connection but, if the need arises, we can deliberately close the connection with the following line of code:

$dbh = null;

Recommended Tutorials for you


Anuj kumar

This is Anuj Kumar. I’m a professional web developer with 5+ years of experience. I write blogs in my free time. I love to learn new technologies and share with others. I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials. .


  1. hi mr anuj kumar… in case if i want to change the root@local to other user for the admin login page… which one do i need to configure first…. I have put car rental system on web server… configured script on config file… and the main page is running ok… but cannot log to admin page… Error: SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO).

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top button