bubble_chart StackLab

Php PDO CRUD Speedrun

9 steps · pending Not started · person_outline Guest
arrow_back Back

PDO Database Connection

Before performing CRUD operations, PHP connects to the MySQL database.

code php
$host = 'localhost';
$db   = 'library_db';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

$options = [
    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, $options);

} catch (PDOException $e) {

    die("Database connection failed: " . $e->getMessage());

}
The $pdo variable is used for all database operations.

login Sign in to save your progress permanently. info Progress is saved in your browser session
format_list_numbered Step 2 of 9