How does PDO in PHP differ in handling database queries compared to the deprecated mysql functions?

PDO in PHP differs from the deprecated mysql functions by providing a more secure and flexible way to interact with databases. PDO supports multiple database drivers, prepared statements to prevent SQL injection attacks, and object-oriented syntax for easier code maintenance. To migrate from mysql functions to PDO, you need to rewrite your database queries using PDO methods.

// 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) {
    die('Connection failed: ' . $e->getMessage());
}

// Query the database using PDO prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Process the query result
if ($user) {
    echo 'User found: ' . $user['username'];
} else {
    echo 'User not found';
}