note 111029 deleted from pdostatement.fetchall by danbrown

From: Date: Thu, 17 Jan 2013 15:21:24 +0000
Subject: note 111029 deleted from pdostatement.fetchall by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193137@lists.php.net to get a copy of this message
Note Submitter: David Rodger ---- Following on from Ant P's note: http://www.php.net/manual/en/pdostatement.fetchall.php#88699 One can also use PDO:FETCH_GROUP|PDO::FETCH_CLASS. This takes the first column as the index of the outer array and the other values as properties of the specified class. <?php /*Query is something like SELECT cp.user_id, c.* FROM categories_posts cp LEFT JOIN categories c ON (cp.cat_id = c.id) WHERE cp.post_id IN (23, 45) */ $results = $stmt->fetchAll(PDO:FETCH_GROUP|PDO::FETCH_CLASS, 'Category'); print_r($results); /*Results are something like: Array ( [23] => Array ( [0] => Category Object ( [id] => 1 [name] => Programming ) [1] => Category Object ( [id] => 2 [name] => PHP ) ) [45] => Array ( [0] => Category Object ( [id] => 1 [name] => Programming ) [1] => Category Object ( [id] => 2 [name] => Python ) ) ) */ ?> That's one query for multiple posts, instead of one for each post. Since results are indexed by the post id, they can be easily attached to the post.

« previous php.notes (#193137) next »