What is the purpose of using PDO in PHP?

When working with databases in PHP, it is important to use a secure and consistent method for interacting with the database. PDO (PHP Data Objects) provides a unified interface for accessing databases, allowing for easier database connectivity and manipulation. It also helps prevent SQL injection attacks by using prepared statements.

// Connect to a MySQL database using PDO
$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);
    echo "Connected to the database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}