How can developers optimize their PHP code for performance when making database queries, especially when transitioning from mysql to mysqli functions?

When transitioning from mysql to mysqli functions for database queries in PHP, developers can optimize their code for performance by utilizing prepared statements. Prepared statements help improve performance by reducing the overhead of repeatedly parsing and compiling the same query. This also helps prevent SQL injection attacks. Developers should also consider using proper indexing on database tables to further optimize query performance.

// Example of using prepared statements with mysqli

// Create a new mysqli connection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a statement
$stmt = $mysqli->prepare("SELECT name, age FROM users WHERE id = ?");

// Bind parameters
$stmt->bind_param("i", $id);

// Set parameter values
$id = 1;

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

// Bind result variables
$stmt->bind_result($name, $age);

// Fetch results
while ($stmt->fetch()) {
    echo "Name: $name, Age: $age <br>";
}

// Close the statement and connection
$stmt->close();
$mysqli->close();