How can PDO be utilized to improve database operations in PHP compared to traditional xtc_db_query functions?

Using PDO in PHP can improve database operations compared to traditional xtc_db_query functions by providing a more secure and flexible way to interact with databases. PDO allows for parameterized queries, which helps prevent SQL injection attacks. Additionally, PDO supports multiple database drivers, making it easier to switch between different database systems without changing your code.

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, PDO::PARAM_INT);
    $stmt->execute();

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

    foreach ($result as $row) {
        // Do something with the data
    }
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}