PDO is the acronym for
PHP Data Object
. PDO is the object abstraction layer to be able to manipulate database data in a standard way. That is, there are no methods specific to each database, but rather PDO defines a standard interface that databases have to support.
In this way we will ensure that a PHP program built with PDO can be used to access any database. Or, at least, in theory that’s how it would be. In this example we are going to connect a DB with PHP PDO.
The first thing to establish a connection with PDO is to create a PDO object.
$db = new PDO()
To instantiate a PDO object we must pass the connection string to the database, the user and the connection password.
In the case that the database is MYSQL the connection string will be.
mysql:host=host_name;dbname=db_name;
In this way the creation of the PDO object will look like this:
$db = new PDO('mysql:host=localhost;dbname=codeline;charset=utf8mb4', 'user', 'password');
To check that we have managed to connect a DB with PHP PDO we are going to dump the connection status. To recover the connection status we use the .getAttribute() method to which we will pass the constant PDO::ATTR_CONNECTION_STATUS.
echo 'Connected to '.$db->getAttribute(PDO::ATTR_CONNECTION_STATUS);
It is important to know that there may be a failure in the connection process. The reasons may be multiple, the host is not accessible, or the database does not exist or the user/password fails,…
This is why we must control errors in PDO. To do this we are going to use a try-catch loop and we will handle the exception PDOException
try {
$db = new PDO('mysql:host=localhost;dbname=codeline;charset=utf8mb4', 'user', 'password');
echo 'Connected to '.$db->getAttribute(PDO::ATTR_CONNECTION_STATUS);
} catch(PDOException $ex) {
echo 'Error connecting to the DB. '.$ex->getMessage();
}
The getMessage() method of the exception will give us information about the problem that has been generated.
In this simple way we have managed to connect a DB with PHP PDO.
