iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

MySQL Connect

Connecting is the first step. Get the credentials, charset, and error mode right once — the rest of the lessons re-use this snippet.

PDO — recommended

PHP
$dsn = 'mysql:host=localhost;dbname=shop;charset=utf8mb4';

try {
    $pdo = new PDO($dsn, 'app_user', getenv('DB_PASS'), [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);
    echo 'connected';
} catch (PDOException $e) {
    error_log($e->getMessage());
    die('Database is unavailable.');
}

Why those three options

OptionWhy
ERRMODE_EXCEPTIONErrors throw; matches the rest of modern PHP.
DEFAULT_FETCH_MODE = FETCH_ASSOCCleaner rows than the default (numeric + assoc).
EMULATE_PREPARES = falseLets the server type-check parameters; safer.

mysqli — OO style

PHP
$mysqli = new mysqli('localhost', 'user', 'pass', 'shop');
if ($mysqli->connect_error) {
    die($mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4');

Storing credentials

Don't hardcode them. Read from environment variables, an .env file (use vlucas/phpdotenv), or a secrets manager:

PHP
$pdo = new PDO(
    sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4',
        getenv('DB_HOST'), getenv('DB_NAME')),
    getenv('DB_USER'),
    getenv('DB_PASS'),
);

One connection per script

Don't open a new PDO inside every function. Build it once at the entry point and pass it (or inject it into a class) wherever it's needed.

Tip: Use a long-lived "app user" role with minimum privileges (SELECT/INSERT/UPDATE/DELETE on your app's tables — never DROP or GRANT). Schema migrations run as a separate, privileged role.

Example

Example
<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'user', 'pass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
echo 'connected';
Try it Yourself »

Exercise

Charset attribute in the DSN.

'mysql:host=localhost;dbname=shop; =utf8mb4'

Test yourself

Q1. Connect-time option to throw on errors is…
Q2. Hard-code passwords?
Q3. EMULATE_PREPARES = false is recommended because…

Discussion

Loading…