Articles

In this article, we will talk about what a PDO is, why is it necessary, and how to work with it.
Let’s start with the fact that for a long time php-programmers have been discussing the fate of the native functions to work with the database: mysql_connect, mysql_query, and others. The fact is that in upcoming versions of PHP data will be erased, these functions will go "Obsolete". Thus PHP developers should force on other tools to work with the database.
Currently, there are two alternatives solutions; mysqli extension and expansion of PDO. In this article, we will discuss PDO.
PDO – PHP Data Objects – is a layer that offers a versatile way to work with multiple databases.
This layer has several advantages:
  • PDO allows you to work with different databases, such as: MYSQL, Oracle, PostgreSQL and many others.
  • PDO allows you to work with a prepared statement
Now let’s talk about all this in more detail.

Connecting to a Database Using PDO

Before you start working with PDO, you must make sure that you have the correct extension – php_pdo_mysql.dll. This can be verified through the function phpinfo(). If everything is okay, you are good to go.
First we need to connect to the database:
PHP

 

xxxxxxxxxx
1

15

 

1

/ / MuSQL

2


3

   $Database = new PDO ("mysql: host = $ host; dbname = $Databasename", $username, $password); 

4


5

/ / PostgreSQL

6


7

   $Database = new PDO ("pgsql: host = $ host; dbname = $Databasename", $username, $password);

8


9

/ / MS SQL

10


11

   $Database = new PDO ("mssql: host = $ host; dbname = $Databasename", $username, $password); 

12


13

/ / SQLite

14


15

   $Database = new PDO ("sqlite: my / database / path / database.db");

As you can see from the example, each database connection string is slightly different from each other
You should always use try/catch when you are trying to connect to the unit, so that on exception we do not disclosed any data to the user.
PHP

 

xxxxxxxxxx
1

 

1

try {

2

   $Database = new PDO ("mysql: host = $ host; dbname = $Databasename", $username, $password); 

3

} 

4

catch (PDOException $ e) { 

5

   echo "Unable to connect to database"; 

6

}

Source de l’article sur DZONE