Header Ads Widget

Responsive Advertisement

PDO (PHP Data Objects)

PDO (PHP Data Objects)


Publisher Anuj Kumar
Course Length 31 mins
Course Language English



Description

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.
PDO Support 12 diffrent database drivers.
Driver name
Supported databases
PDO_CUBRID
Cubrid
PDO_DBLIB
FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD
Firebird
PDO_IBM
IBM DB2
PDO_INFORMIX
IBM Informix Dynamic Server
PDO_MYSQL
MySQL 3.x/4.x/5.x
PDO_OCI
Oracle Call Interface
PDO_ODBC
ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL
PostgreSQL
PDO_SQLITE
SQLite 3 and SQLite 2
PDO_SQLSRV
Microsoft SQL Server / SQL Azure
PDO_4D
4D
All of these drivers are not necessarily available on your system , you can find list ob available in your system by using this command 
print_r(PDO::getAvailableDrivers()); 
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_HOST','localhost');
define('DB_USER','your user name');
define('DB_PASS','your user password');
define('DB_NAME','your database name');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,
DB_USER, DB_PASS,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
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; 






Post a Comment

0 Comments