note 111362 added to pdostatement.fetch

From: Date: Mon, 11 Feb 2013 16:07:49 +0000
Subject: note 111362 added to pdostatement.fetch
Groups: php.notes 
Request: Send a blank email to php-notes+get-193605@lists.php.net to get a copy of this message
When using PDO::FETCH_COLUMN in a while loop, it's not enough to just use the value in the while statement as many examples show: <?php while ($row = $stmt->fetch(PDO::FETCH_COLUMN)) { print $row; } ?> If there are 5 rows with values 1 2 0 4 5, then the while loop above will stop at the third row printing only 1 2. The solution is to either explicitly test for false: <?php while (($row = $stmt->fetch(PDO::FETCH_COLUMN)) !== false) { print $row; } ?> Or use foreach with fetchAll(): <?php foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) { print $row; } ?> Both will correctly print 1 2 0 4 5. ---- Server IP: 69.147.83.199 Probable Submitter: 79.172.193.241 ---- Manual Page -- http://php.net/manual/en/pdostatement.fetch.php Edit -- https://master.php.net/note/edit/111362 Del: integrated -- https://master.php.net/note/delete/111362/integrated Del: useless -- https://master.php.net/note/delete/111362/useless Del: bad code -- https://master.php.net/note/delete/111362/bad+code Del: spam -- https://master.php.net/note/delete/111362/spam Del: non-english -- https://master.php.net/note/delete/111362/non-english Del: in docs -- https://master.php.net/note/delete/111362/in+docs Del: other reasons-- https://master.php.net/note/delete/111362 Reject -- https://master.php.net/note/reject/111362 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193605) next »