devnotes.

Connecting with PDO

PDO (PHP Data Objects) is the modern, recommended way to talk to databases from PHP — it provides one consistent API across MySQL, PostgreSQL, SQLite, and others, unlike the older, MySQL-only mysqli extension.

try {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
        'db_user',
        'db_password',
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION means database errors throw catchable PDOExceptions instead of silently failing or triggering a warning — the recommended setting for every project.

Simple queries:

$stmt = $pdo->query('SELECT * FROM users');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['name'];
}

$all = $pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);

Never store real database credentials directly in source code committed to version control — load them from environment variables or a .env file (excluded via .gitignore) instead.

PHP PDO: Connecting to a Database | DevNotes