ADOdb Library for PHP Manual
Prev Select Statement Next

Select Statement

Task: Connect to the Access Northwind DSN, display the first 2 columns of each row.

In this example, we create a ADOConnection object, which represents the connection to the database. The connection is initiated with PConnect, which is a persistent connection. Whenever we want to query the database, we call the ADOConnection.Execute() function. This returns an ADORecordSet object which is actually a cursor that holds the current row in the array fields[]. We use MoveNext() to move from row to row.

NB: A useful function that is not used in this example is SelectLimit, which allows us to limit the number of rows shown.

<?php
    
include('adodb.inc.php'); # load code common to ADOdb
    
$conn = &ADONewConnection('access'); # create a connection
    
$conn->PConnect('northwind'); # connect to MS-Access, northwind DSN

    
$recordSet = &$conn->Execute('select * from products');

    if (!
$recordSet)
        print 
$conn->ErrorMsg();
    else
        while (!
$recordSet->EOF) {
            print 
$recordSet->fields[0].' '.$recordSet->fields[1].'<BR>';
            
$recordSet->MoveNext();
        }    
$recordSet->Close(); # optional
    
$conn->Close(); # optional

?>

The $recordSet returned stores the current row in the $recordSet->fields array, indexed by column number (starting from zero). We use the MoveNext() function to move to the next row. The EOF property is set to true when end-of-file is reached. If an error occurs in Execute(), we return false instead of a recordset.

The $recordSet->fields[] array is generated by the PHP database extension. Some database extensions only index by number and do not index the array by field name. To force indexing by name - that is associative arrays - use the SetFetchMode function. Each recordset saves and uses whatever fetch mode was set when the recordset was created in Execute() or SelectLimit().

    $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 get the number of rows in the select statement, you can use $recordSet->RecordCount(). Note that it can return -1 if the number of rows returned cannot be determined.


Prev Home Next
Tutorial Up Advanced Select with Field Objects

Sponsored by phpLens