PDO helps you connect to databases safely and easily. It makes talking to databases simple and secure.
PDO connection setup in PHP
<?php $dsn = 'mysql:host=your_host;dbname=your_dbname;charset=utf8'; $username = 'your_username'; $password = 'your_password'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully."; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
The $dsn string tells PDO where the database is and which one to use.
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION helps catch errors clearly.
<?php $dsn = 'mysql:host=localhost;dbname=testdb;charset=utf8'; $username = 'root'; $password = ''; $pdo = new PDO($dsn, $username, $password); ?>
<?php $dsn = 'pgsql:host=localhost;port=5432;dbname=testdb'; $username = 'postgres'; $password = 'secret'; $pdo = new PDO($dsn, $username, $password); ?>
<?php $dsn = 'sqlite:/path/to/database.db'; $pdo = new PDO($dsn); ?>
This program tries to connect to a MySQL database named mydatabase on the local machine. It prints a success message if it connects or an error message if it fails.
<?php $dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8'; $username = 'user123'; $password = 'pass123'; try { $pdo = new PDO($dsn, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully."; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
Always use try-catch to handle connection errors gracefully.
Use UTF-8 charset in DSN to avoid character problems.
Keep your database username and password safe and never share them publicly.
PDO lets you connect to databases in a safe and easy way.
Use DSN, username, and password to set up the connection.
Handle errors with try-catch and set error mode to exceptions.
Practice
PDO in PHP?Solution
Step 1: Understand PDO's role
PDO is a PHP extension designed to connect to databases in a secure and consistent way.Step 2: Compare other options
Other options like creating HTML, handling sessions, or sending emails are unrelated to PDO.Final Answer:
To connect to databases securely and easily -> Option AQuick Check:
PDO = Secure database connection [OK]
- Confusing PDO with HTML or session functions
- Thinking PDO sends emails
- Assuming PDO is for file handling
Solution
Step 1: Check DSN format for MySQL
The correct DSN format is 'mysql:host=hostname;dbname=database_name'.Step 2: Verify options
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); uses the correct DSN format with host and dbname separated by semicolon and includes username and password.Final Answer:
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); -> Option DQuick Check:
DSN format = 'mysql:host=...;dbname=...' [OK]
- Omitting 'mysql:' prefix
- Using slashes instead of semicolons
- Missing 'host=' keyword
$dsn = 'mysql:host=localhost;dbname=testdb';
try {
$pdo = new PDO($dsn, 'user', 'wrongpass');
echo 'Connected';
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}Solution
Step 1: Analyze connection attempt
The code tries to connect with username 'user' but a wrong password 'wrongpass'.Step 2: Understand error handling
PDO throws a PDOException on failure, caught by catch block, which prints the error message.Final Answer:
Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'user'@'localhost' (using password: YES) -> Option BQuick Check:
Wrong password triggers exception message [OK]
- Expecting 'Connected' despite wrong password
- Ignoring try-catch block
- Assuming no output on failure
try {
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}Solution
Step 1: Review DSN and credentials
The DSN string is correct and includes host and dbname properly.Step 2: Check error mode setting
PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION are valid constants to enable exceptions on errors.Step 3: Verify syntax
All lines end with semicolons and try-catch is properly structured.Final Answer:
No error, code is correct -> Option CQuick Check:
Correct DSN and error mode = no error [OK]
- Using wrong error mode constants
- Forgetting semicolons
- Miswriting DSN string
Solution
Step 1: Check error mode setting
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION ensures exceptions on errors.Step 2: Verify try-catch placement
The error mode must be set inside the try block before any database operations, so exceptions are caught properly.Step 3: Analyze options
try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } correctly sets error mode inside try and catches PDOException with detailed message.Final Answer:
try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } -> Option AQuick Check:
Error mode exception + try-catch = try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } [OK]
- Setting error mode outside try block
- Using wrong error mode constants
- Catching wrong exception type
Ready to prove it?
Pass the test and this pattern moves unknown
