PHP has two main extensions for talking to MySQL.
| mysqli | PDO | |
|---|---|---|
| Databases | MySQL and MariaDB only | MySQL, PostgreSQL, SQLite and more |
| Style | Procedural and object-oriented | Object-oriented |
| Prepared statements | Yes | Yes, with named placeholders too |
| Switching database | Rewrite the code | Mostly change the connection string |
Both are fine. This course uses PDO: it is the more flexible one, and most frameworks use it.
The connection details
To connect, PHP needs four things:
| Detail | Example |
|---|---|
| Host | 127.0.0.1 or localhost |
| Database name | shop |
| Username | root (local only) or a dedicated user |
| Password | Your database password |
On local servers such as XAMPP, the user is often root with an empty password. Never do that on a live site. Create a separate user with a strong password and only the rights it needs.
A first connection with PDO
<?php
declare(strict_types=1);
$dsn = "mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "shop_user", "a-strong-password", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
echo "Connected to MySQL.";
} catch (PDOException $e) {
error_log($e->getMessage());
exit("Could not connect to the database.");
}
Connected to MySQL.
What the pieces mean:
$dsn(data source name): where and what to connect to. It starts with the driver name (mysql:).charset=utf8mb4makes the connection use full UTF-8.- The options array sets safe defaults. The next two lessons explain each one.
try/catchhandles a failed connection. The message goes to the log. The visitor sees a short, harmless sentence.
The same with mysqli (for comparison)
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("127.0.0.1", "shop_user", "a-strong-password", "shop");
$mysqli->set_charset("utf8mb4");
echo "Connected with mysqli.";
Is the extension installed?
<?php
var_dump(extension_loaded("pdo_mysql") || extension_loaded("pdo_sqlite"));
bool(true)
If pdo_mysql is missing, enable extension=pdo_mysql in php.ini and restart the web server.
Common connection errors
| Message (shortened) | Meaning |
|---|---|
Access denied for user | Wrong username or password |
Unknown database 'shop' | The database does not exist (check the name) |
Connection refused | MySQL is not running, or the host or port is wrong |
could not find driver | pdo_mysql is not enabled |
Do not hide the password in plain view
Never put real credentials in a file that is inside the public web folder or in Git. Read them from environment variables or a config file outside the web root. Database Connections shows how.