What are the best practices for handling varying column numbers in a database query result in PHP?

When handling varying column numbers in a database query result in PHP, it is important to dynamically retrieve and process the columns to ensure flexibility. One approach is to use the `fetch_assoc()` method to fetch rows as associative arrays, allowing you to access columns by their names instead of indexes. Additionally, you can use functions like `mysqli_num_fields()` to determine the number of columns in a result set and iterate over the columns accordingly.

// Assuming $result is the result of a database query

// Get the number of columns in the result set
$num_columns = mysqli_num_fields($result);

// Fetch rows as associative arrays
while ($row = mysqli_fetch_assoc($result)) {
    // Process each column dynamically
    for ($i = 0; $i < $num_columns; $i++) {
        $column_name = mysqli_fetch_field_direct($result, $i)->name;
        $column_value = $row[$column_name];
        // Process the column data as needed
        echo $column_name . ': ' . $column_value . '<br>';
    }
}