Learn how to connect to a mysql database and query it using the PDO extension in PHP
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>
Article discussion
Share your thoughts about this article.
Log in or create an account to comment.
No comments yet. Be the first to join the discussion.