Establish a secure and modern database connection in PHP using PDO , ideal for scalable applications.
π Why Use PDO?
PDO (PHP Data Objects) is a database access layer that provides a consistent interface for working with multiple databases. It's more secure and flexible than using mysqli_* functions and supports prepared statements to prevent SQL injection.
π§ Basic PDO Connection
<?php $host = 'localhost'; $db = 'testdb'; $user = 'root'; $pass = ''; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); echo "β
Connected successfully!"; } catch (PDOException $e) { echo "β Connection failed: " . $e->getMessage(); } ?> π§ Code Explanation
- $dsn: Data source name, includes host, database, charset
- $options: Configuration for error handling and fetch modes
- PDO::ERRMODE_EXCEPTION: Throws exceptions on errors
- PDO::FETCH_ASSOC: Returns associative arrays
- PDO::EMULATE_PREPARES: False for real prepared statements
β Best Practices
- Use try-catch blocks for handling connection failures
- Never expose raw connection errors in production
- Use
.envfiles or configuration files to store credentials - Always use UTF-8 to support international characters
π Whatβs Next?
After connecting to the database, you can:
- Run
SELECT,INSERT,UPDATEqueries with$pdo->prepare() - Use transactions with
beginTransaction(),commit(), androllBack() - Fetch results using
fetch()orfetchAll()