What are the potential advantages of using PDO over other methods in PHP for database operations?

When working with databases in PHP, using PDO (PHP Data Objects) provides a more secure and flexible way to interact with databases compared to other methods like MySQLi. PDO allows for the use of prepared statements, which help prevent SQL injection attacks. Additionally, PDO supports multiple database types, making it easier to switch between different databases without changing your code.

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