What are the best practices for handling character encoding and conversion in PHP mysqli queries to avoid errors like "Fatal error: Uncaught Error: Call to a member function fetch_assoc() on null"?

When dealing with character encoding and conversion in PHP mysqli queries, it is important to ensure that the data being retrieved from the database is properly encoded to avoid errors like "Fatal error: Uncaught Error: Call to a member function fetch_assoc() on null". One way to handle this is by setting the correct character encoding for the mysqli connection using the mysqli_set_charset() function.

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

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

// Set character encoding
$mysqli->set_charset("utf8");

// Perform a query
$result = $mysqli->query("SELECT * FROM table");

// Check if the query was successful
if ($result) {
    // Fetch data
    while ($row = $result->fetch_assoc()) {
        // Process data
    }
} else {
    echo "Error: " . $mysqli->error;
}

// Close connection
$mysqli->close();