Skip to content
PHP Logo

How can PHP developers effectively handle database connections using PDO?

When working with databases in PHP, developers can effectively handle database connections using PDO (PHP Data Objects). PDO provides a consistent interface for accessing different types of databases, making it easier to switch between databases without changing much code. To establish a database connection using PDO, developers need to create a new PDO object with the appropriate database credentials.

php
// Establishing a database connection using PDO
$host = 'localhost';
$dbname = 'my_database';
$username = 'my_username';
$password = 'my_password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected to database successfully";
} catch (PDOException $e) {
    die("Failed to connect to database: " . $e->getMessage());
}