What are the best practices for handling MySQL result sets in PHP functions to avoid errors and ensure data integrity?

When handling MySQL result sets in PHP functions, it is important to properly check for errors and ensure data integrity to prevent issues such as SQL injection attacks or data corruption. To do this, you should always use prepared statements with parameterized queries to prevent SQL injection, validate and sanitize user input before executing queries, and handle errors gracefully by checking for errors after each query execution.

// Example of handling MySQL result sets in PHP functions to avoid errors and ensure data integrity

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

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

// Prepare a statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Validate and sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

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

// Check for errors
if (!$result) {
    die("Error executing query: " . $mysqli->error);
}

// Fetch and process the result set
while ($row = $result->fetch_assoc()) {
    // Process each row of data
}

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