How does using PDO compare to creating a custom database class in PHP?

Using PDO in PHP provides a more standardized and secure way to interact with databases compared to creating a custom database class. PDO offers built-in support for prepared statements, which helps prevent SQL injection attacks. It also allows for easier switching between different database types without changing much code.

// Using PDO to connect to a database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}