note 120175 added to pdostatement.fetchall
| From: | jeroen dot deklerk at hotmail dot com | Date: | Wed, 16 Nov 2016 11:47:02 +0000 |
| Subject: | note 120175 added to pdostatement.fetchall | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-207117@lists.php.net to get a copy of this message | ||
I was having trouble with returning PDO query results in arrays, due to the structure of the results
of those queries (query array with arrays for results inside). Now when executing a fetchAll() on a
query you get the following:
Array ( [0] = Array ( [key1] => "value1", [key2] => "value2") [1] = Array(
[key1] => "value1", [key2] => "value2") )
This is a smaller array, but return results in a HUGE database this way and it quickly becomes
IMPPOSIBRU to read out the array given.
This is where the glorious foreach comes in! We all know the basic writing of a foreach (foreach
($array as $key => $value) {...}), but with query results there's a twist, as both the $key
AND $value variables are arrays, where $key is the array of the query containing the result arrays
and $value is/are the result array(s) themselves.
So in this foreach we have to talk directly to $value to get our results! This would look something
like this:
<?php
foreach ($query as $key => $value) {
return $value["key2"];
}
?>
This already does the job, but to return them in arrays we have to change our return code a little
bit, like so:
<?php
foreach ($query as $key => $value) {
return array (
"key1" => $value["key1"],
"key2" => $value["key2"]
);
}
?>
This foreach loops through the query array, just like the firs one, but the return code just
doesn't return the keys representing the result arrays ($key) and returns only keys from inside
the result arrays, stored in $value. This gives us an array looking like this:
Array ( [key1] => "value1", [key2] => "value2")
This should return all the values in your array, if written properly. I'm still having problems
with the foreach not returning ALL results, but this note was mainly to show how it can be returned
in an array.
----
Server IP: 72.52.91.14
Probable Submitter: 188.205.121.134
----
Manual Page -- http://php.net/manual/en/pdostatement.fetchall.php
Edit -- https://master.php.net/note/edit/120175
Del: integrated -- https://master.php.net/note/delete/120175/integrated
Del: useless -- https://master.php.net/note/delete/120175/useless
Del: bad code -- https://master.php.net/note/delete/120175/bad+code
Del: spam -- https://master.php.net/note/delete/120175/spam
Del: non-english -- https://master.php.net/note/delete/120175/non-english
Del: in docs -- https://master.php.net/note/delete/120175/in+docs
Del: other reasons-- https://master.php.net/note/delete/120175
Reject -- https://master.php.net/note/reject/120175
Search -- https://master.php.net/manage/user-notes.php