Labels

Other Ways To Fetch Result Set Rows

fetch() accepts an optional fetch-mode argument indicating what type of value to return. This section
describes some common mode values. Assume in each case that the following query has just been issued to
produce a result set:
$sth = $dbh->query ("SELECT name, category FROM animal");
• PDO::FETCH_NUM
Return each row of the result set as an array containing elements that correspond to the columns named
in the SELECT statement and that are accessed by numeric indices beginning at 0:
while ($row = $sth->fetch (PDO::FETCH_NUM))
printf ("Name: %s, Category: %s\n", $row[0], $row[1]);
• PDO::FETCH_ASSOC
Return each row as an array containing elements that are accessed by column name:
while ($row = $sth->fetch (PDO::FETCH_ASSOC))
printf ("Name: %s, Category: %s\n", $row["name"], $row["category"]);
• PDO::FETCH_BOTH
Return each row as an array containing elements that can be accessed either by numeric index or by column
name:
while ($row = $sth->fetch (PDO::FETCH_BOTH))
{
printf ("Name: %s, Category: %s\n", $row[0], $row[1]);
printf ("Name: %s, Category: %s\n", $row["name"], $row["category"]);
}
• PDO::FETCH_OBJ
Return each row as an object. In this case, you access column values as object properties that have the
same names as columns in the result set:
while ($row = $sth->fetch (PDO::FETCH_OBJ))
printf ("Name: %s, Category: %s\n", $row->name, $row->category);
If you invoke fetch() with no argument, the default fetch mode is PDO::FETCH_BOTH unless you
change the default before fetching the rows:
• The query() method accepts an optional fetch-mode argument following the statement string:
$sth = $dbh->query ("SELECT name, category FROM animal", PDO::FETCH_OBJ);
while ($row = $sth->fetch ())
printf ("Name: %s, Category: %s\n", $row->name, $row->category);
• Statement handles have a setFetchMode() method to set the mode for subsequent fetch() calls:
$sth->setFetchMode (PDO::FETCH_OBJ);
while ($row = $sth->fetch ())
printf ("Name: %s, Category: %s\n", $row->name, $row->category);
Another way to fetch results is to bind variables to the result set columns with bindColumn(). Then you
fetch each row using the PDO::FETCH_BOUND fetch mode. PDO stores the column values in the variables,
and fetch() returns TRUE instead of a row value while rows remain in the result set:
$sth = $dbh->query ("SELECT name, category FROM animal");
$sth->bindColumn (1, $name);
$sth->bindColumn (2, $category);
while ($sth->fetch (PDO::FETCH_BOUND))
printf ("Name: %s, Category: %s\n", $name, $category);