How can the use of PDO in PHP improve database query performance compared to mysql_ functions?

Using PDO in PHP can improve database query performance compared to mysql_ functions because PDO supports prepared statements, which can be reused with different parameters, reducing the overhead of parsing the query each time. PDO also provides a consistent interface for working with different types of databases, allowing for easier migration between database systems. Additionally, PDO helps prevent SQL injection attacks by automatically escaping input parameters.

// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
$options = array(
    PDO::ATTR_EMULATE_PREPARES => false, // Disable emulated prepares
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION // Enable error reporting
);

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

// Prepare a statement and bind parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$id = 1;

// Execute the statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Display the results
foreach ($results as $row) {
    echo $row['name'] . '<br>';
}