How to get field name in mysqli using php with example

How to get field name in mysqli using php with example

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.

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

Loading...

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.

Related posts

(1) Comments

  • User Pic

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

Write a comment