Explain it simply
Explain it simply
Before PHP can run any query it must open a connection: a conversation with the database server that needs to know where the server is (the host), which database to use, and who you are (username and password). PDO packs those facts into a DSN string plus a username and password, and gives you back one $pdo object. Every later step in the next lessons goes through that object. On local XAMPP the host is usually localhost and the user is root with an empty password, but a production server must never look like that.
Opening the connection is also the first place something can go wrong: a wrong password, a stopped server, a missing database. A good connection function therefore decides up front what happens on failure, instead of letting PHP print a stack trace for the visitor.
Problem → Why → Solution
The problem: credentials in the code, errors on the screen
The quickest connection code puts the host, the root user and an empty password directly in the script, then calls die() with the driver's error message if it fails. It works on a laptop, but on a real server it commits secrets into git, runs the whole site as the all-powerful root user, and when the database is down it prints text such as the host name and user name straight onto the page for anyone to read. Every page that copies the snippet also opens its own connection, so a slow database gets slower under a storm of connections.
<?php
// Quick and dangerous: secrets in the code, details shown to visitors
$conn = new mysqli("localhost", "root", "", "thutatech_demo");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // printed on the page
}
echo "Database connected successfully.";Why this is risky
Anything committed to git is hard to take back, so a password in the source is effectively public. A root account can drop tables and read every database on the server, so one SQL injection bug becomes a total loss. And an error message on the page tells attackers which host and user exist. The fix is configuration outside the code, a least-privilege account, and an error path that logs details privately.
Core concept: DSN, options, credentials and one connection
A PDO connection is created with new PDO($dsn, $username, $password, $options). The DSN is a string: the driver name, a colon, then key=value pairs separated by semicolons. For MySQL that is mysql:host=localhost;port=3306;dbname=thutatech_demo;charset=utf8mb4; for SQLite it is sqlite: followed by a file path, or sqlite::memory: for a throwaway database that lives in RAM. The constructor throws a PDOException when the connection fails, whatever error mode you chose, so the new PDO call is the one you wrap in try/catch.
The options array is where you set behaviour once for the whole connection. ATTR_ERRMODE => ERRMODE_EXCEPTION makes every database problem throw a PDOException instead of quietly returning false; PHP 8 already defaults to this, but writing it keeps the code obvious and portable to older versions. ATTR_DEFAULT_FETCH_MODE => FETCH_ASSOC makes fetch() return arrays keyed by column name only, instead of the default mix of names and numbers that doubles every row. ATTR_EMULATE_PREPARES => false asks the MySQL driver to use real server-side prepared statements; its default is to emulate them inside PHP, which usually works but handles types and edge cases differently, so many teams turn it off.
Credentials do not belong in the source code. Read them from environment variables (getenv('DB_HOST')), which the web server, the container or a .env loader sets, and keep any config file outside the public web root and outside version control. Use a dedicated database account with only the rights the application needs (SELECT, INSERT, UPDATE and DELETE on its own database) rather than root, so a leaked password or an injection bug cannot drop tables or touch other databases.
Finally, treat the connection as a shared resource. Create it once per request, near the start (a bootstrap file or a small connect() function), and pass it into the classes that need it, as you saw with constructors in the classes lesson. Opening a new connection for every query is slow, and hidden global connections make code hard to test. On failure, catch PDOException, write the real message to the log and show the visitor a short generic message, because depending on configuration the stack trace of an uncaught exception can include constructor arguments such as the DSN.
- DSN says where and which database
- Credentials prove who you are
- Options set the rules for the call
- One connection, shared by the request
Connect once, configure once, and keep the secrets outside the code.
General pattern
<?php
$dsn = 'driver:key=value;key=value';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
// log $e->getMessage(), then show a generic error page
}The DSN holds the driver and key=value pairs, and the options array sets behaviour for the whole connection. Wrapping new PDO in try/catch lets you handle the PDOException yourself when the connection fails.
Example: a connect() function with safe defaults
The function takes a DSN and optional credentials and returns a configured PDO. The DSN and credentials come from environment variables when they exist, so the same script runs against SQLite here and against MySQL on a real server just by setting APP_DB_DSN, APP_DB_USER and APP_DB_PASSWORD; with nothing set it falls back to an in-memory SQLite database.
For MySQL on XAMPP you would set APP_DB_DSN to mysql:host=localhost;dbname=thutatech_demo;charset=utf8mb4 and not change a single other line.
<?php
declare(strict_types=1);
function connect(string $dsn, ?string $user = null, ?string $password = null): PDO
{
return new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
}
// Real apps read these from the environment; the fallback keeps the demo runnable
$dsn = getenv('APP_DB_DSN') ?: 'sqlite::memory:';
$pdo = connect($dsn, getenv('APP_DB_USER') ?: null, getenv('APP_DB_PASSWORD') ?: null);
echo 'Connected using driver: ', $pdo->getAttribute(PDO::ATTR_DRIVER_NAME), "\n";
$row = $pdo->query("SELECT 1 + 1 AS two, 'Aye' AS name")->fetch();
echo 'Query works, row fetched as: ', json_encode($row), "\n";Code breakdown
- Line 4
function connect(string $dsn, ?string $user = null, ?string $password = null): PDOConnection creation lives in one function, so the options are changed in a single place. ?string = null lets SQLite skip credentials, and the return type PDO promises a configured object.
- Line 7
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,Every database error throws a PDOException. Without it, older PHP versions could let a failed query pass quietly as a false return value.
- Line 8
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,fetch() and fetchAll() now return arrays keyed by column name only, such as ['two' => 2, 'name' => 'Aye'], and you no longer repeat fetch(PDO::FETCH_ASSOC) all over your code.
- Line 9
PDO::ATTR_EMULATE_PREPARES => false,Asks for real prepared statements on MySQL. The SQLite driver accepts the option too, but the difference is visible on the MySQL driver.
- Line 14
$dsn = getenv('APP_DB_DSN') ?: 'sqlite::memory:';getenv() returns false when the variable is not set and the ?: (Elvis) operator swaps that for the fallback. In production code you usually should not keep a fallback; fail early if the setting is missing (see the deeper section).
- Line 17
echo 'Connected using driver: ', $pdo->getAttribute(PDO::ATTR_DRIVER_NAME), "\n";getAttribute() reports the driver in use, and the following query proves the connection works and that fetch() returns an array keyed by column name.
Connected using driver: sqlite
Query works, row fetched as: {"two":2,"name":"Aye"}Anatomy of a DSN
A DSN is nothing exotic: a driver name, a colon, then settings separated by semicolons. The keys allowed differ by driver, so check the PHP manual for yours. The charset goes in the DSN because it decides the encoding of the text sent over this connection.
DSN anatomy
-----------
mysql:host=localhost;port=3306;dbname=thutatech_demo;charset=utf8mb4
^ ^ ^
| | +-- connection charset
| +-- key=value pairs separated by semicolons
+-- driver name: selects the pdo_mysql driver| Database | Example DSN | Note |
|---|---|---|
| MySQL / MariaDB | mysql:host=127.0.0.1;port=3306;dbname=app;charset=utf8mb4 | Always include charset=utf8mb4 |
| SQLite (file) | sqlite:/path/to/app.db | PHP needs write access to the folder |
| SQLite (memory) | sqlite::memory: | The database vanishes when the script ends |
| PostgreSQL | pgsql:host=localhost;port=5432;dbname=app | Username and password go to the constructor |
When the connection fails
The code below tries two DSNs that cannot connect. The first is an SQLite file in a folder that does not exist, and the second is an unknown driver name. Notice that tryConnect() catches the PDOException, writes the detail to the log and returns null, so the visitor sees only the sentence about the service being unavailable. The 'Log would say' lines show what reaches the log.
<?php
declare(strict_types=1);
function tryConnect(string $dsn): ?PDO
{
try {
return new PDO($dsn, null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (PDOException $e) {
// The detail goes to the log only, never to the visitor
error_log('DB connection failed: ' . $e->getMessage());
return null;
}
}
$pdo = tryConnect('sqlite:/no/such/folder/app.db');
if ($pdo === null) {
echo "Sorry, the service is temporarily unavailable.\n";
}
// What the log line contained, for comparison
try {
new PDO('sqlite:/no/such/folder/app.db');
} catch (PDOException $e) {
echo 'Log would say: ', $e->getMessage(), "\n";
}
// A missing driver is a different failure, also thrown by the constructor
try {
new PDO('nosuchdriver:host=localhost');
} catch (PDOException $e) {
echo 'Log would say: ', $e->getMessage(), "\n";
}Knowing what these messages mean makes debugging faster. The SQLite and missing-driver messages come straight from running the code; the MySQL rows are the messages that typically appear, listed from MySQL's documentation rather than reproduced here.
| Message | Usual cause |
|---|---|
| could not find driver | The driver extension (pdo_mysql, pdo_sqlite) is not enabled in php.ini |
| SQLSTATE[HY000] [14] unable to open database file | SQLite: wrong path, or the folder is not writable |
| [1045] Access denied for user ... | MySQL (expected wording): wrong username, password or host privilege |
| [1049] Unknown database '...' | MySQL (expected wording): the dbname database has not been created yet |
| [2002] Connection refused | MySQL (expected wording): the server is not running, or the host or port is wrong |
Reading credentials from the environment
Rather than hiding a missing setting behind a fallback, it is better to fail early and clearly. The requireEnv() function below throws a RuntimeException that names what is missing. putenv() is used only to demonstrate; in reality the server, the container or a .env loader sets the environment.
<?php
function requireEnv(string $name): string
{
$value = getenv($name);
if ($value === false || $value === '') {
throw new RuntimeException("Missing environment variable: $name");
}
return $value;
}
// Normally the server, the container or a .env loader sets this
putenv('DEMO_DB_HOST=127.0.0.1');
$host = requireEnv('DEMO_DB_HOST');
echo "Host is $host\n";
try {
requireEnv('DEMO_DB_NAME');
} catch (RuntimeException $e) {
echo 'Config error: ', $e->getMessage(), "\n";
}On MySQL a low-privilege account for the application is created once by an administrator. The SQL below is MySQL and MariaDB syntax; SQLite has no such user system, because whoever can open the file can use it.
-- Run once by a MySQL administrator (MySQL / MariaDB syntax)
CREATE DATABASE thutatech_demo CHARACTER SET utf8mb4;
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'use-a-long-random-password';
GRANT SELECT, INSERT, UPDATE, DELETE ON thutatech_demo.* TO 'app_user'@'localhost';One connection, handed to the code that needs it
This reuses the constructor passing (dependency injection) from the classes lesson. ContactRepository and AuditLog both receive $pdo through their constructors, so both share a single connection. A test can simply hand in an in-memory database instead, with no global state to work around.
<?php
declare(strict_types=1);
final class ContactRepository
{
public function __construct(private PDO $pdo) {}
public function add(string $name): void
{
$this->pdo->prepare('INSERT INTO contacts (name) VALUES (?)')->execute([$name]);
}
public function count(): int
{
return (int) $this->pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();
}
}
final class AuditLog
{
public function __construct(private PDO $pdo) {}
public function record(string $event): void
{
$this->pdo->prepare('INSERT INTO audit (event) VALUES (?)')->execute([$event]);
}
public function count(): int
{
return (int) $this->pdo->query('SELECT COUNT(*) FROM audit')->fetchColumn();
}
}
// One connection, created once at start-up
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec('CREATE TABLE contacts (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
$pdo->exec('CREATE TABLE audit (id INTEGER PRIMARY KEY, event TEXT NOT NULL)');
// ...and handed to every class that needs the database
$contacts = new ContactRepository($pdo);
$audit = new AuditLog($pdo);
$contacts->add('Aye');
$contacts->add('Kyaw');
$audit->record('two contacts imported');
echo 'contacts: ', $contacts->count(), ', audit entries: ', $audit->count(), "\n";In real projects
Where this shows up in real projects
Real projects keep connection settings in one place. Laravel reads them from a .env file into config/database.php, Symfony references environment variables from its configuration, and containers inject them at start-up, so the same code runs against a different database in development, testing and production. Hosts usually give you a separate database user per site; you create the database and the user in the control panel (or with the GRANT statements above), and the application account never gets rights beyond its own database.
Because a connection is relatively expensive, a request opens one and reuses it; under heavy load teams add connection limits, health checks and sometimes a connection pooler in front of the database, but that is a deployment concern, not something page code should reimplement. Most importantly, a failed connection is something to expect now and then: the page should return a friendly 503, and the details should land in a log that someone monitors.
Common mistakes
Common mistakes
1. The root user, an empty password and credentials in the source
Copying the root and empty-password code that is convenient on XAMPP into production removes every safeguard. Use an environment variable and a least-privilege account from the start so there is nothing to fix on deploy day.
2. Showing the error to visitors with die($e->getMessage())
The message can contain the host, the username and sometimes more. In the catch block log it with error_log() and return a generic message with an HTTP 503 status.
3. Connecting to a database that does not exist yet
On MySQL, a dbname in the DSN that has not been created yet should be expected to produce an Unknown database error. Create the database first through a setup script or the control panel, and only then connect the application to it.
4. Leaving charset out of the DSN
Depending on the server's defaults the connection may use another charset, and non-Latin text such as Myanmar can be corrupted. Put charset=utf8mb4 in every MySQL DSN.
5. Opening a new connection for every query
Writing new PDO inside every function opens many connections per request, wastes time on handshakes, and lets settings drift apart. Create it once and pass it through constructors.
Best practices
Best practices
- Centralise connection creation in one function and set ERRMODE_EXCEPTION, FETCH_ASSOC and EMULATE_PREPARES => false in that one place.
- Read credentials from the environment and fail clearly at start-up when one is missing.
- Give the application its own database user with only SELECT, INSERT, UPDATE and DELETE, never root.
- Log the PDOException and show visitors a generic message with a 503 status.
Mini challenge
Mini challenge: a connection factory for two drivers
Write a function that builds a DSN from a config array and another that returns null instead of letting an exception escape when the connection fails. Then loop over four configs.
- buildDsn(array $cfg): string returns mysql:host=...;port=...;dbname=...;charset=utf8mb4 for 'mysql' (defaults localhost and 3306), sqlite:<name> for 'sqlite', and throws InvalidArgumentException otherwise
- tryConnect(string $dsn): ?PDO creates the PDO with exception errors, logs a PDOException and returns null
- In the loop print the DSN, really connect only the sqlite configs, and print ' connected' or ' database unavailable'
- For the mysql config print ' (not connecting in this demo)', and for an unknown driver print the exception message
<?php
declare(strict_types=1);
// TODO: buildDsn(array $cfg): string
// 'mysql' -> mysql:host=<host>;port=<port>;dbname=<name>;charset=utf8mb4
// (defaults: host localhost, port 3306)
// 'sqlite' -> sqlite:<name>
// anything else -> throw InvalidArgumentException("Unsupported driver: ...")
// TODO: tryConnect(string $dsn): ?PDO
// create the PDO with exception errors; on PDOException log the detail with
// error_log() and return null instead of letting the exception escape
$configs = [
['driver' => 'mysql', 'host' => '127.0.0.1', 'name' => 'thutatech_demo'],
['driver' => 'sqlite', 'name' => ':memory:'],
['driver' => 'sqlite', 'name' => '/no/such/folder/app.db'],
['driver' => 'oracle', 'name' => 'legacy'],
];
// TODO: for each config print "DSN: <dsn>" (or the unsupported-driver message).
// Only sqlite configs are really connected: print " connected" or
// " database unavailable". For the mysql config print
// " (not connecting in this demo)".Expected: DSN: mysql:host=127.0.0.1;port=3306;dbname=thutatech_demo;charset=utf8mb4 (not connecting in this demo) DSN: sqlite::memory: connected DSN: sqlite:/no/such/folder/app.db database unavailable Unsupported driver: oracle
Show hint
Write buildDsn with a match expression and use a throw expression in the default arm. In the loop wrap buildDsn() in try/catch and connect only after that succeeded.
Show solution
<?php
declare(strict_types=1);
function buildDsn(array $cfg): string
{
return match ($cfg['driver']) {
'mysql' => sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
$cfg['host'] ?? 'localhost',
$cfg['port'] ?? 3306,
$cfg['name']
),
'sqlite' => 'sqlite:' . $cfg['name'],
default => throw new InvalidArgumentException(
"Unsupported driver: {$cfg['driver']}"
),
};
}
function tryConnect(string $dsn): ?PDO
{
try {
return new PDO($dsn, null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
} catch (PDOException $e) {
error_log('Database connection failed: ' . $e->getMessage());
return null;
}
}
$configs = [
['driver' => 'mysql', 'host' => '127.0.0.1', 'name' => 'thutatech_demo'],
['driver' => 'sqlite', 'name' => ':memory:'],
['driver' => 'sqlite', 'name' => '/no/such/folder/app.db'],
['driver' => 'oracle', 'name' => 'legacy'],
];
foreach ($configs as $cfg) {
try {
$dsn = buildDsn($cfg);
} catch (InvalidArgumentException $e) {
echo $e->getMessage(), "\n";
continue;
}
echo "DSN: $dsn\n";
if ($cfg['driver'] !== 'sqlite') {
echo " (not connecting in this demo)\n";
continue;
}
echo tryConnect($dsn) !== null ? " connected\n" : " database unavailable\n";
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Connect with new PDO($dsn, $user, $password, $options); the DSN names the driver and connection details, and the constructor always throws a PDOException when it cannot connect.
- Set ERRMODE_EXCEPTION, FETCH_ASSOC and EMULATE_PREPARES => false once, inside one connect() function.
- Credentials come from the environment, and the application connects with a low-privilege account rather than root.
- Create the connection once and pass it through constructors; on failure log the detail and show visitors a generic message.
PDO Prepared Statements — PHP Documentation Group