Search code examples
phpadodb-php

How to get "field names" using PHP ADOdb?


I'm using PHP ADOdb and I can get the result set:

$result = &$db->Execute($query);

How do I get the field names from that one row and loop through it?

(I'm using access database if that matters.)


Solution

  • It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1

    $db->SetFetchMode(ADODB_FETCH_NUM);
    $rs1 = $db->Execute('select * from table');
    $db->SetFetchMode(ADODB_FETCH_ASSOC);
    $rs2 = $db->Execute('select * from table');
    
    print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
    print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
    

    To loop through a set of results:

    $result = &$db->Execute($query);
    foreach ($result as $row) {
        print_r($row);
    }