note 90692 added to pdostatement.fetchall

From: Date: Tue, 05 May 2009 07:21:58 +0000
Subject: note 90692 added to pdostatement.fetchall
Groups: php.notes 
Request: Send a blank email to php-notes+get-154213@lists.php.net to get a copy of this message
PLEASE BE AWARE: If you do an OUTER LEFT JOIN and set PDO FetchALL to PDO::FETCH_ASSOC, any primary key you used in the OUTER LEFT JOIN will be set to a blank if there are no records returned in the JOIN. For example: <?php //query the product table and join to the image table and return any images, if we have any, for each product $sql = "SELECT * FROM product, image LEFT OUTER JOIN image ON (product.product_id = image.product_id)"; $array = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($array); ?> The resulting array will look something like this: Array ( [0] => Array ( [product_id] => [notes] => "this product..." [brand] => "Best Yet" ... The fix is to simply specify your field names in the SELECT clause instead of using the * as a wild card, or, you can also specify the field in addition to the *. The following example returns the product_id field correctly: <?php $sql = "SELECT *, product.product_id FROM product, image LEFT OUTER JOIN image ON (product.product_id = image.product_id)"; $array = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($array); ?> The resulting array will look something like this: Array ( [0] => Array ( [product_id] => 3 [notes] => "this product..." [brand] => "Best Yet" ... ---- Server IP: 64.71.164.2 Probable Submitter: 96.229.227.148 ---- Manual Page -- http://www.php.net/manual/en/pdostatement.fetchall.php Edit -- https://master.php.net/note/edit/90692 Del: integrated -- https://master.php.net/note/delete/90692/integrated Del: useless -- https://master.php.net/note/delete/90692/useless Del: bad code -- https://master.php.net/note/delete/90692/bad+code Del: spam -- https://master.php.net/note/delete/90692/spam Del: non-english -- https://master.php.net/note/delete/90692/non-english Del: in docs -- https://master.php.net/note/delete/90692/in+docs Del: other reasons-- https://master.php.net/note/delete/90692 Reject -- https://master.php.net/note/reject/90692 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#154213) next »