PHP & MySQL · Lesson 2 of 11
Connecting PHP with MySQL
Connect through PDO and report connection failures safely.
Lesson
PDO provides a consistent interface for database connections. Read credentials from protected configuration, enable exception errors, and specify a character set in the DSN. Do not display database exceptions to end users; log details securely and return a generic error response.
The example uses MySQL UTF-8 and exception mode; credentials belong in environment configuration.
Further guidance
Use migrations to version schema changes, constraints to protect relationships, and prepared statements for every dynamic value. Scope writes with a precise condition, check affected rows, and use transactions when multiple statements must succeed together. Store credentials outside source control.
Practice task: Create a fresh example for Connecting PHP with MySQL. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Connecting PHP with MySQL
PHP
$pdo = new PDO(
'mysql:host=127.0.0.1;dbname=app;charset=utf8mb4',
getenv('DB_USERNAME'),
getenv('DB_PASSWORD'),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
Expected output
A PDO connection or an exception for the application to handle
Key points
- Connect through PDO and report connection failures safely.
- Use prepared statements for values and constraints for data integrity.
- Scope writes carefully and verify their result.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.