Connect PHP to MySQL Using PDO (Safe Setup)
Set up a database connection using PDO with proper error handling and best practices.
PDO is the recommended way to talk to MySQL in modern PHP because it supports prepared statements and clean error handling.
Step 1: Create database config
Create `config.php`:
```php <?php $DB_HOST = "localhost"; $DB_NAME = "tutorial_app"; $DB_USER = "root"; $DB_PASS = "";
$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4";
try { $pdo = new PDO($dsn, $DB_USER, $DB_PASS, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); } catch (PDOException $e) { die("Database connection failed"); } ?> ```
Why charset utf8mb4 matters
It supports emojis and full Unicode. Without it, some characters break.
Best practice
Do not echo real database errors in production. Log them.
> Next: Prepared statements, the #1 SQL injection defense.