How to Access a Database with PDO/mysqli

January 2017

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


Published by deri58. Latest update on June 25, 2015 at 12:55 PM by jak58.
This document, titled "How to Access a Database with PDO/mysqli," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).