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:
Now let’s talk about all this in more detail.
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
/ / MuSQL
$Database = new PDO ("mysql: host = $ host; dbname = $Databasename", $username, $password);
/ / PostgreSQL
$Database = new PDO ("pgsql: host = $ host; dbname = $Databasename", $username, $password);
/ / MS SQL
$Database = new PDO ("mssql: host = $ host; dbname = $Databasename", $username, $password);
/ / SQLite
$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
try {
$Database = new PDO ("mysql: host = $ host; dbname = $Databasename", $username, $password);
}
catch (PDOException $ e) {
echo "Unable to connect to database";
}
There is no special method to close the connection in PDO, we can close the connection by overriding the variable:
$Database = null;
#database #tutorial #database access #pdo #php data objects