What are the key differences between using mysql functions and PDO in PHP for database operations?

When working with databases in PHP, using PDO (PHP Data Objects) is generally preferred over using mysql functions due to its improved security, flexibility, and support for multiple database types. PDO provides a more object-oriented approach to database operations and allows for prepared statements, which help prevent SQL injection attacks. Additionally, PDO is easier to maintain and migrate to different database systems if needed.

// Using PDO for database operations in PHP
try {
    $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $row) {
        // Process data
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}