How to Access a Database with PDO/mysqli

Ask a question
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
.
Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team