What best practices should be followed when handling database queries and result sets in PHP scripts?

When handling database queries and result sets in PHP scripts, it is important to properly sanitize input to prevent SQL injection attacks, use prepared statements to prevent SQL injection and improve performance, and handle errors gracefully to avoid exposing sensitive information.

// Connect to the database
$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);
}

// Prepare and execute a query using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = "john_doe";
$stmt->execute();
$result = $stmt->get_result();

// Fetch and output results
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row['username'] . "<br>";
}

// Close the connection
$stmt->close();
$conn->close();