Skip to content

mysqli_fetch_field: 5 Ways to Get Column Names in PHP

mysqli_fetch_field: 5 Ways to Get Column Names in PHP

Suppose, you want to show all records of the database table and you don't know about the table detail like how many columns and how many rows then you need a function mysqli_fetch_field.

mysqli_fetch_field($mysql_query)

With the help of this function, you will get all the field names of your table. You can store these values in an array for further use to extract all value of these fields.

mysqli_fetch_field: when to read result metadata

Use this function when the column descriptions should come from the query result itself. It returns one field description at a time, so the loop must stop when no further field information is available.

Understand the result before reading its columns

Get column names in MySQLi from a query result, rather than from the table in the abstract. The result describes the columns selected by that particular statement. For example, a query that selects only first_name and email has two result fields even if the underlying table contains many more columns. This makes result metadata useful for dynamic reports, exports, and generic table views.

Choose the columns you actually need

A wildcard query such as SELECT * is convenient for a small demonstration, but production code is usually clearer when it names the required columns. Explicit selection makes the output contract visible, avoids fetching values that the page does not use, and makes changes to the table less likely to alter the page unexpectedly. The metadata methods still work with either form.

Remember that a successful query is a prerequisite. If mysqli_query fails, it does not return a normal result object, so trying to fetch field information from the failure value leads to another error. Check the query result first; handle or log the database error in a way appropriate to the application instead of printing sensitive server details to visitors.

Read the field name property

Each field description returned by mysqli_fetch_field is an object. Its name property is the column name exposed by the result. Other useful metadata can identify the table or database, describe the original column name where an alias is involved, or report the field type. Treat those extra properties as descriptive metadata, not as a replacement for a carefully designed query.

while($mysql_query_fields = mysqli_fetch_field($mysql_query)){
        $mysql_fields[] = $mysql_query_fields->name;
}

MySQL is a multi-threaded or multi-user database management system having more than 11 million installations. It is the world’s second-largest most popular and widely used open-source database.

Using MySQL is free of cost for developers, but enterprises have to buy the licensed version. It is supported by the Oracle and based on Structured Query Language. It supports a wide range of operating systems like Windows, Linux, and Unix, etc.

Top 50 MySQL Interview Questions and Answers

After holding all values in an array you can use for each forgets all values. Let's take a complete example:

<table width="75%" align="center" style="background-color:#F8F8F8" cellpadding="7" cellspacing="3">
    <?php
    $mysql_query = mysqli_query($connection, "Select * from country Limit 0,10");
    echo "<tr style='background-color:#999999'>";
    while($mysql_query_fields = mysqli_fetch_field($mysql_query)){
        $mysql_fields[] = $mysql_query_fields->name;
        echo "<th align='left'>".ucfirst($mysql_query_fields->name)."</th>";
    }
    echo "</tr>";
    
    while($mysql_rows = mysqli_fetch_array($mysql_query)){
    echo "<tr>";
        foreach($mysql_fields as $fields){
            echo "<td>".$mysql_rows[$fields]."</td>";
        }
    echo "</tr>";
    }
?>
</table>

I this example you don't know about your table structure but you have received all fields with value.

Build a reliable dynamic table

Keep field discovery separate from row output

The existing example first walks over the result's field descriptions to print headings and remember each field name. It then iterates over the rows and uses the saved names to select matching values. That separation is helpful: the same ordered list of fields drives both the header and each row, reducing the risk that one column is labelled incorrectly.

Code editor displayed on a computer monitor for a database tutorial
A code editor provides the setting for exploring query results and column metadata. · Photo: Startup Stock Photos / Openverse (CC0)

For a smaller implementation, mysqli_fetch_fields returns the field descriptions as an array, which can be useful when you need to inspect or reuse the whole set. mysqli_num_fields tells you how many columns the result contains, while mysqli_fetch_field reads the next field description one at a time. Choose the method that keeps your code easiest to follow; do not mix methods casually if you are depending on the current field pointer.

Steps for reading MySQLi column metadata safely
Read MySQLi Column Metadata

Account for aliases and duplicate labels

SQL aliases affect the label exposed for a selected expression. For example, a computed expression can be given a readable result name with AS, and that alias becomes the practical key to use in the output row. If two selected columns have the same label, associative access can be ambiguous and a generated table may show confusing headings. Give selected expressions distinct aliases when the output needs stable, unique names.

Metadata describes the query result, not every rule in the database schema. If a page needs constraints, indexes, or full table-definition details, use the appropriate schema-inspection approach and permissions. Do not assume the field metadata alone provides everything needed to build a form or validate writes.

Handle display, empty results, and common mistakes

Escape values when rendering HTML

Database values are data, not trusted markup. When placing a value into an HTML cell, escape it for the output context, for example with htmlspecialchars using the appropriate character encoding. This is especially important for text that can be submitted by users. Escaping the displayed value protects the page from interpreting stored characters as HTML or script; it is separate from using parameterized SQL when receiving query input.

Column headings should also be treated as output. A heading may come from an alias or a computed expression, so escape it just as carefully. Avoid building SQL identifiers from unchecked request values. Prepared-statement placeholders bind values, not table or column identifiers; if users choose a sort column, map a small set of allowed choices to known identifiers.

Check result state and field iteration

  • Check that the query returned a result before fetching fields or rows.
  • Expect no rows to be a valid result: headings may still exist even when the row loop runs zero times.
  • Do not call a single-field fetch repeatedly without accounting for its advancing field pointer.
  • If you must restart field iteration, use the documented pointer-reset method or obtain a fresh result as appropriate.
  • Free a result when your code is finished with it, especially in longer-running processes.

A common source of confusion is mixing the result from one query with the connection or result variable from another. Use descriptive names such as $result, $field, and $row, and check the query assignment carefully. Also remember that fetching rows consumes the row cursor. If another part of the program needs to read the same rows again, plan for buffering or run a separate query rather than assuming a consumed result starts over.

When should you use column metadata?

Good fits and poor fits

Metadata is a practical fit for admin reports, export utilities, generic diagnostic screens, and tools that display a result whose fields are selected dynamically. It can also help a reusable component create a header row from a query without hard-coding every label.

For a fixed customer-facing page, explicit field names and deliberate labels are often better. They make accessibility labels, translations, formatting, and business meaning clearer than automatically exposing database column names. A database identifier such as acct_status may not be a useful label for a visitor; present a friendly label separately when that matters.

Test realistic cases

Test a result with several columns, a result with an alias, a query returning zero rows, and a value containing characters such as ampersands or angle brackets. Also test the exact query variants used by the application, because the selected columns determine the metadata. These checks catch problems that a single happy-path example will not reveal.

Keep the field list tied to the result that produced it. If you execute another query and reuse the old array of names, the row keys may no longer match. Treat each query result and its metadata as one unit, and the generated table will be easier to maintain.

For the next steps after discovering result fields, see the PHP/MySQLi query workflow; for shared setup across pages, use the reusable MySQLi connection guide.

1 Comment

  • Fantastic. I was using sprintf() based on PHP docs' example when echo allows using capitalization. Thanks.

Write a comment