What are the advantages of using PDO over mysqli functions in PHP?

When working with databases in PHP, using PDO (PHP Data Objects) over mysqli functions provides several advantages. PDO supports multiple database drivers, making it easier to switch between different databases without changing your code. PDO also provides a more secure way to interact with databases by using prepared statements, which helps prevent SQL injection attacks. Additionally, PDO is object-oriented, making it easier to work with and maintain code.

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