What are some best practices for transitioning from mysql functions to PDO in PHP code?

When transitioning from mysql functions to PDO in PHP code, it is important to rewrite the database queries using PDO prepared statements to prevent SQL injection attacks and improve code security. Additionally, PDO provides a more object-oriented approach to interacting with databases, making code more maintainable and easier to read.

// Replace mysql functions with PDO in PHP code
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

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

// Prepare and execute a query using PDO prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

// Fetch results using PDO fetch methods
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Process results
}