What best practices should be followed when handling MySQL query results in PHP, based on the discussions in the forum?

When handling MySQL query results in PHP, it is important to properly check for errors, fetch the results in a safe manner, and free up resources after use. One common best practice is to use prepared statements to prevent SQL injection attacks and ensure data integrity.

// Example of handling MySQL query results in PHP using prepared statements

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

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

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

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

// Bind the results to variables
$stmt->bind_result($id, $name);

// Fetch and display the results
while ($stmt->fetch()) {
    echo "ID: $id, Name: $name <br>";
}

// Free up resources
$stmt->close();
$mysqli->close();