note 111029 added to pdostatement.fetchall

From: Date: Tue, 08 Jan 2013 11:29:26 +0000
Subject: note 111029 added to pdostatement.fetchall
Groups: php.notes 
Request: Send a blank email to php-notes+get-192836@lists.php.net to get a copy of this message
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. ---- Server IP: 113.20.13.217 Probable Submitter: 49.176.38.171 ---- Manual Page -- http://php.net/manual/en/pdostatement.fetchall.php Edit -- https://master.php.net/note/edit/111029 Del: integrated -- https://master.php.net/note/delete/111029/integrated Del: useless -- https://master.php.net/note/delete/111029/useless Del: bad code -- https://master.php.net/note/delete/111029/bad+code Del: spam -- https://master.php.net/note/delete/111029/spam Del: non-english -- https://master.php.net/note/delete/111029/non-english Del: in docs -- https://master.php.net/note/delete/111029/in+docs Del: other reasons-- https://master.php.net/note/delete/111029 Reject -- https://master.php.net/note/reject/111029 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#192836) next »