Unleash your creativity
πŸŽƒ Danny 2 weeks ago
it's october y'all. you know what that means. SPOOKY SCARY SKELETONS πŸ•ΊπŸ»
Latest Additions Wish something
πŸ‚ nick 3 hours ago
ugh can't get myself to design anything lately, so I guess no seasonal themes here this year </3

Connecting to a database

Connecting to a database
Written by nick
27.05.2025

1 What you'll need

To connect to a MySQL database using PHP, you'll need to know 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 Adding character encoding and error handling

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 emojis
  • ERRMODE_EXCEPTION shows clear error messages
  • EMULATE_PREPARES = false is better for security
  • FETCH_ASSOC makes query results easier to work with

4 Using your database 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>";
}

Next: Learn how to run safe queries with PDO