faqts : Computers : Programming : Languages : PHP : Database Backed Sites : MySQL

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

22 of 24 people (92%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I fetch the field name and data for every row of a database query result?
How can I get the column (field) name from a database query result row in MySQL?

Jul 2nd, 1999 18:27
Nathan Wallace, unknown unknown, Fred Isler


To work with fields in MySQL you need to know about the following
functions:

    http://www.php.net/manual/function.mysql-num-fields.php3
    http://www.php.net/manual/function.mysql-field-name.php3

Here is an example that will print the field names and their values from
each row in a MySQL query result:

    <?php
        $dbh = mysql_connect("host", "foo1", "foo2");
        mysql_select_db("foo3");
        $query = "select * from foo";

        $result = mysql_query($query, $dbh);

        $fields = mysql_num_fields($result);

        while ($row=mysql_fetch_array($result)) {
                for ($i=0; $i<$fields; $i++)  {
                        $name=mysql_field_name($result, $i);
                        echo "$name = $row[$name]<BR>\n";
                }
                echo "<br><br>\n";
        }
    <?

Should give you output like this:

field1 = id1
field2 = blahblah
field3 = done

field1 = id2
field2 = blah
field3 = doneagain

(etc)