note 92505 added to mysqli-stmt.bind-result
| From: | uramihsayibok at osu1 dot php dot net | Date: | Mon, 27 Jul 2009 20:35:44 +0000 |
| Subject: | note 92505 added to mysqli-stmt.bind-result | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158791@lists.php.net to get a copy of this message | ||
A note to people to want to return an array of results - that is, an array of all the results from
the query, not just one at a time.
<?php
// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);
$results = array();
while ($mysqli_stmt_object->fetch()) {
$results[] = $byref_array_for_fields;
}
?>
This will NOT work. $results will have a bunch of arrays, but each one will have a reference to
$byref.
PHP is optimizing performance here: you aren't so much copying the $byref array into $results
as you are *adding* it. That means $results will have a bunch of $byrefs - the same array repeated
multiple times. (So what you see is that $results is all duplicates of the last item from the
query.)
hamidhossain (01-Sep-2008) shows how to get around that: inside the loop that fetches results you
also have to loop through the list of fields, copying them as you go. In effect, copying everything
individually.
Personally, I'd rather use some kind of function that effectively duplicates an array than
write my own code. Many of the built-in array functions don't work, apparently using references
rather than copies, but a combination of array_map and create_function does.
<?php
// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);
// returns a copy of a value
$copy = create_function('$a', 'return $a;');
$results = array();
while ($mysqli_stmt_object->fetch()) {
// array_map will preserve keys when done here and this way
$results[] = array_map($copy, $byref_array_for_fields);
}
?>
All these problems would go away if they just implemented a fetch_assoc or even fetch_array for
prepared statements...
----
Server IP: 64.71.164.2
Probable Submitter: 64.81.169.38
----
Manual Page -- http://www.php.net/manual/en/mysqli-stmt.bind-result.php
Edit -- https://master.php.net/note/edit/92505
Del: integrated -- https://master.php.net/note/delete/92505/integrated
Del: useless -- https://master.php.net/note/delete/92505/useless
Del: bad code -- https://master.php.net/note/delete/92505/bad+code
Del: spam -- https://master.php.net/note/delete/92505/spam
Del: non-english -- https://master.php.net/note/delete/92505/non-english
Del: in docs -- https://master.php.net/note/delete/92505/in+docs
Del: other reasons-- https://master.php.net/note/delete/92505
Reject -- https://master.php.net/note/reject/92505
Search -- https://master.php.net/manage/user-notes.php