Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fetch vs. fetch_object in PDO, which to use when?

Status
Not open for further replies.

peterv12

Technical User
Dec 31, 2008
108
US
I've searched the PHP documentation, and can't find an answer for this. When coding PHP using PDO, what is the difference between using fetch and using fetch_object? Everything I've read about them seems to say they do exactly the same thing.
Thanks,
Peter V.
 
nope.

the fetchObject() method is a shorthand form for $statement->fetch( PDO::FETCH_OBJ )

the fetch method can accept a variety of constants as the first argument that causes the method to return the data in different formats. the fetchObject() method will only return the data as an anonymous (or defined) object.

Code:
try{
  $statement = $pdo->prepare('Select * from table');
  $statement->execute();
  while ($row = $statement->fetchObject()):
     //do something with $row
  endwhile;
} catch (PDOException $e) {
  print_r($e);
}
is equivalent to

Code:
try{
  $statement = $pdo->prepare('Select * from table');
  $statement->execute();
  while ($row = $statement->[red]fetch( PDO::FETCH_OBJ )[/red]):
     //do something with $row
  endwhile;
} catch (PDOException $e) {
  print_r($e);
}
 
Thanks jpadie! I did some more searching of the PHP manual after reading your reply, and it makes sense now!

PETERV
17" MacBook Pro
Snow Leopard 10.6.7
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top