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<?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<?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<?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<?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<?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<?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();
  }
?>
Задание 1

Establish a connection to your database using the method described in the lesson.