How to Access a Database with PDO/mysqli

December 2016

This article explains how to access a database in PHP using MySQLi or PDO.

PDO

PDO provide support to manage multiple database systems (up to 12 different databasese driver). The basic structure to connect to a database and handle errors is as follows:

try {
$bdd = new PDO( ... );
} catch(PDOException $e) {
echo $e->getMessage();
}


Only the lines required for the creation of the PDO object will be given in the following examples.

mysql

$host = 'localhost';
$user = 'username';
$password = 'password';
$dbname = 'ccm'; // name of database
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);

sqlite

$file = "/path/to/base.sqlite";
$bdd = new PDO("sqlite:$file");


SQLite has another advantage: we can create temporary blank database in the memory, which can be very useful for development, test queries or use a database with the generated data:

$bdd = new PDO("sqlite::memory");

mysqli

Object oriented

$host = 'localhost';
$user = 'username';
$password = 'password';
$dbname = 'ccm'; // Name of database
$db = new mysqli($host, $user, $password, $dbname);
if ($bdd->connect_error) {
echo 'Connection error (' . $bdd->connect_errno . ') ' . $bdd->connect_error;
}

Procedural

$host = 'localhost';
$user = 'username';
$password = 'password';
$dbname = 'ccm'; // Name of database
$bdd = mysqli_connect($host, $user, $password, $dbname);
if (!$bdd) {
echo 'Connection error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error();
}

Error Handling

The error handling described above is very basic. It will only display the error message and won't prevent the above functions from being executed when connection to the database fails
.

Related :

This document entitled « How to Access a Database with PDO/mysqli » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.