What best practices should be followed when handling database connections and query results in PHP scripts to avoid errors and improve performance?

When handling database connections and query results in PHP scripts, it is important to properly manage resources to avoid errors and improve performance. This can be achieved by following best practices such as closing database connections when they are no longer needed, freeing up memory by releasing query results after processing them, and using prepared statements to prevent SQL injection attacks.

// Establishing a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Performing a query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

// Processing query results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Process each row
    }
} else {
    echo "0 results";
}

// Free up memory by releasing query results
$result->free();

// Closing the database connection
$conn->close();