How can the use of PDO improve the efficiency and security of PHP code?

Using PDO (PHP Data Objects) can improve the efficiency and security of PHP code by providing a more secure way to interact with databases through prepared statements, which help prevent SQL injection attacks. PDO also allows for better error handling and supports multiple database types, making it a more versatile and reliable option for database operations in PHP.

// Connect to a MySQL database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'root';
$password = '';

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