DBI Fetch Data

fetchrow_array

To fetch the results of a SELECT command a row at a time you can use $sth->fetchrow_array(). It returns a new row at each call or the undefined value when no more data is left (this can be used as loop condition):

while ( @row = $sth->fetchrow_array() ) {

print "@row";

}

rows

Alternatively you can use the $sth->rows() function for a loop condition. It returns the number of rows affected by the last row affecting command, or -1 if the number of rows is not known or not available (the rows function is not supported by all database drivers). Example:

$rows = $sth->rows();

for ($i = 0; $i < $rows; $i++) 
{
@row = $sth->fetchrow_array();
print "@row";
}

fetchrow_arrayref

$sth->fetchrow_arrayref() fetches the next row of data and returns a reference to an array holding the field values. Null fields are returned as undef values in the array. This is the fastest way to fetch data.

If there are no more rows or if an error occurs, then fetchrow_arrayref returns an undef.

Note that the same array reference is returned for each fetch.

Example:

while ( $ref = $sth->fetchrow_arrayref() ) 
{
print "@{$ref}\n";
}

fetchrow_hashref

$sth->fetchrow_hashref() fetches the next row of data and returns it as a reference to a hash containing field name and field value pairs. Null fields are returned as undef values in the hash. Example:

while ( $ref = $sth->fetchrow_hashref() ) 
{
print "$$ref{'column1'} \t $$ref{'value1'}\n";
}

 

fetchall_arrayref

 

$sth->fetchall_arrayref() can be used to fetch all the data. It returns a reference to an array that contains one reference per row. Example:

$ref = $sth->fetchall_arrayref;
foreach $row ( @{$ref} ) {
print "@$row\n";
}

Last modified: Monday, 2 April 2012, 02:25 AM

Skip Navigation

Navigation

Skip OpenGurukulSkip Settings

Settings