Returning an instance of a class from PDO

PDO can create and return an object(s) of a specific class. It can be a little tricky getting it to work though…

With fetchAll() you can pass ( PDO:FETCH_CLASS, ‘class_name’ ) directly

$sql = sprintf( 'select * from %s where prod_id=:prod_id', TABLE );
$findProducts = $this->db->prepare( $sql );
$findProduct->execute();
$products = $findProducts->fetchAll( PDO::FETCH_CLASS, 'Product' );

But with fetch() you must initiate it with setFetchMode()

$sql = sprintf( 'select * from %s where prod_id=:prod_id', TABLE );
$findProduct = $this->db->prepare( $sql );
$findProduct->setFetchMode( PDO::FETCH_CLASS, 'Product' );
$findProduct->execute();
$product = $findProduct->fetch( PDO::FETCH_CLASS );

Add a response

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">