pull-icon
logo-mobile

PDO Database Connection

Home/Forums/PDO Database Connection

EmmaS

today at 04:58

Learn how to connect to a mysql database and query it using the PDO extension in PHP

<?php
declare(strict_types=1);

// Database connection settings
$dsn  = 'mysql:host=localhost;dbname=db_name;charset=utf8mb4';
$user = 'db_user';
$pass = 'db_password';

try {
    $pdo = new PDO(
        $dsn,
        $user,
        $pass,
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]
    );
} catch (PDOException $e) {
    http_response_code(500);
    exit("Database connection failed.");
}

// Query using prepared statement (best practice)
$stmt = $pdo->query("
    SELECT username, country
    FROM users
    ORDER BY username ASC
");

$people = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>People List</title>
    <style>
        body {
            font-family: system-ui, sans-serif;
            background: #f7f9fc;
            padding: 40px;
        }
        .card {
            background: white;
            padding: 25px 30px;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.05);
            max-width: 500px;
            margin: auto;
        }
        .person {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .person:last-child {
            border-bottom: none;
        }
        .username {
            font-weight: 600;
        }
        .country {
            color: #666;
        }
    </style>
</head>
<body>

<div class="card">
    <h2>People List</h2>

    <?php if ($people): ?>
        <?php foreach ($people as $row): ?>
            <div class="person">
                <span class="username"><?= htmlspecialchars($row['username']) ?></span>
                <span class="country"> — <?= htmlspecialchars($row['country']) ?></span>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>No records found.</p>
    <?php endif; ?>
</div>

</body>
</html>

Leave a Comment

You must be logged in to post a reply.


BellOnline provides fast, reliable UK hosting designed for modern radio and web projects. Optimised servers, strong security, and excellent uptime ensure your station runs smoothly.
MixStream delivers broadcast-grade radio streaming with outstanding stability, crystal-clear audio, and powerful performance even during peak listener hours. Perfect for hobby stations and professional broadcasters alike.


Your secure download link has been emailed to:

Goto BellOnline Now!