Connecting to a database
1. What you'll need
To connect to a MySQL database using PHP, you'll need the following:
- Host – usually
localhost - Database name
- Username and Password
You can usually create a database and find these details in your hosting dashboard (like cPanel or Plesk). If a database was created for you, just look up the credentials or ask your hosting support.
2. A simple connection with PDO
Here's a basic connection example using PDO and an array to keep your settings organized:
<?php
$dbConfig = [
'host' => 'localhost',
'name' => 'yourdatabasename',
'user' => 'yourdatabaseuser',
'password' => 'yourpassword'
];
try {
$pdo = new PDO(
"mysql:host={$dbConfig['host']};dbname={$dbConfig['name']}",
$dbConfig['user'],
$dbConfig['password']
);
} catch (PDOException $e) {
die('Database connection failed.');
}
3. A clean, reliable connection
Let's improve the connection by setting the character encoding, enabling proper error handling, and validating the config values. This version is already solid enough to reuse across your project.
<?php
$dbConfig = [
'host' => 'localhost',
'name' => 'yourdatabasename',
'user' => 'yourdatabaseuser',
'password' => 'yourpassword',
'charset' => 'utf8mb4'
];
// Validates config
if (empty($dbConfig['host']) || empty($dbConfig['name']) || empty($dbConfig['user'])) {
exit('Database host, name, and user cannot be empty.');
}
try {
$pdo = new PDO(
"mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}",
$dbConfig['user'],
$dbConfig['password'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
// Test the connection
$pdo->query('SELECT 1');
} catch (PDOException $e) {
die('Database connection failed.');
}
return $pdo;
You can save this as database.php and include it wherever you need a database connection.
charset=utf8mb4— handles all characters, even emojisERRMODE_EXCEPTION— shows clear error messagesEMULATE_PREPARES = false— better for securityFETCH_ASSOC— makes query results easier to work with
4. Using your connection file
Now you can include the file and use the connection in your project like this:
<?php
$pdo = include 'database.php';
$query = $pdo->query('SELECT * FROM users');
$users = $query->fetchAll();
foreach ($users as $user) {
echo 'User: ' . htmlspecialchars($user['username']) . "<br>";
}