Database Connection via PDO in PHP
Let's establish a connection to the database via PDO. First, let's write the access credentials into variables:
<?php
$host = 'localhost'; // hostname (usually always like this)
$db = 'test'; // database name
$user = 'root'; // username for DB login
$pass = 'root'; // password for DB login
?>
Now we need to form a string
in a special format. In this string,
we must specify the type of DB used
(usually, 'mysql'),
the hostname, and the database name:
<?php
$dsn = "mysql:host=$host; dbname=$db; charset=utf8";
?>
Then we create an array of PDO options, which we will use in the process of work (don't delve into them for now):
<?php
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
?>
Now we can perform the connection to the database using the variables declared above:
<?php
$pdo = new PDO($dsn, $user, $pass, $opt);
?>
The code above will either connect
to the database or throw an exception.
Therefore, it is more correct to wrap the connection
in a try-catch construct:
<?php
try {
$pdo = new PDO($dsn, $user, $pass, $opt);
echo 'DB is connected';
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
The full code will look like this:
<?php
$host = 'localhost';
$db = 'test';
$user = ''; // username for DB login
$pass = ''; // password for DB login
$charset = 'utf8';
$dsn = "mysql:host=$host; dbname=$db; charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $opt);
echo 'DB is connected';
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Establish a connection to your database using the method described in the lesson.