MySQL Intro
PHP talks to MySQL through two main extensions: mysqli and PDO. Both ship with PHP. For new code, prefer PDO — it's portable across databases.
The choice
| Extension | Style | Multi-DB? |
|---|---|---|
| mysqli | Procedural and OO API | MySQL / MariaDB only |
| PDO | Object-oriented | MySQL, PostgreSQL, SQLite, SQL Server, … |
| mysql (no i) | Old, removed in PHP 7.0 | Don't use |
PDO — the modern default
PHP
$pdo = new PDO(
'mysql:host=localhost;dbname=shop;charset=utf8mb4',
'user',
'pass',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
],
);
foreach ($pdo->query('SELECT id, name FROM customers') as $row) {
echo $row['name'], PHP_EOL;
}
mysqli — for legacy code or one-off scripts
PHP
$mysqli = new mysqli('localhost', 'user', 'pass', 'shop');
$mysqli->set_charset('utf8mb4');
$result = $mysqli->query('SELECT id, name FROM customers');
while ($row = $result->fetch_assoc()) {
echo $row['name'], PHP_EOL;
}
Connection string essentials
host— usuallylocalhostor an IP/hostname.dbname— which database to use.charset=utf8mb4— the only sane choice in 2026. Plainutf8in MySQL is a 3-byte subset.- Production: never commit credentials. Read from env vars / a secrets manager.
What to read next
The lessons in this section walk you through connecting, creating tables, inserting/selecting/updating/deleting data, and prepared statements. Each uses PDO; mysqli equivalents are flagged in the references.
Tip: For real apps, layer a query builder or ORM on top. Eloquent (Laravel), Doctrine, Cycle — all of them speak PDO underneath and give you migrations + relations + sane defaults.
Example
Example
<?php // PHP talks to MySQL via mysqli or PDO. // PDO is generally preferred for new code. echo 'See the connect lesson for a working example.';Try it Yourself »
Exercise
Modern recommended PHP DB API.
Use
Three letters.
Discussion
Loading…