How to get field name in mysqli using php

How to get table field name in MySQL using php

How to get field name in mysqli using php

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

 

mysqli_fetch_field($mysql_query)

 

With the help of this function you will get all field name of your table. You can store these value in 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;
}

 

After holding all value in array you can use foreach for get 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.

 

Top