What are the advantages of using PDO over the mysql_ functions in PHP for database operations, and how can it improve the security of the application?

Using PDO over the mysql_ functions in PHP for database operations provides several advantages such as support for multiple database drivers, prepared statements for preventing SQL injection attacks, and object-oriented approach for easier database interaction. This can improve the security of the application by reducing the risk of SQL injection vulnerabilities.

// Using PDO for database operations
$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);
    
    // Prepare a statement to prevent SQL injection
    $stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    
    // Fetch results
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Use results
    foreach ($results as $row) {
        echo $row['username'] . '<br>';
    }
    
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}