PHP: mysqli_stmt_bind_result - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysqli_stmt_close mysqli_stmt_bind_param

Last updated: Sat, 27 Jan 2007

view this page in

# mysqli_stmt_bind_result

(PHP 5)

mysqli_stmt_bind_result

(no version information, might be only in CVS)

stmt->bind_result -- Binds variables to a prepared statement for result storage

## Description

Procedural style:

bool mysqli_stmt_bind_result ( mysqli_stmt stmt, mixed &var1 [, mixed &...] )

Object oriented style (method):

class mysqli_stmt {
bool bind_result ( mixed &var1 [, mixed &...] )
}

mysqli_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables `var1, ...`.

> Замечание: Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

> A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.

## Возвращаемые значения

Возвращает `TRUE` в случае успешного завершения или `FALSE` в случае возникновения ошибки.

## Смотрите также

mysqli_stmt_bind_param(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_prepare(), mysqli_stmt_init(), mysqli_stmt_errno() и mysqli_stmt_error().

## Примеры

Пример 1. Object oriented style

`<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>`

Пример 2. Procedural style

`<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
mysqli_stmt_execute($stmt);
/* bind variables to prepared statement */
mysqli_stmt_bind_result($stmt, $col1, $col2);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf("%s %s\n", $col1, $col2);
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>`

Результат выполнения данного примера:

    AFG Afghanistan
    ALB Albania
    DZA Algeria
    ASM American Samoa
    AND Andorra

add a note User Contributed Notes
mysqli_stmt_bind_result
Typer85 at gmail dot com
29-Dec-2006 06:01
`Through some testing, I managed to find an answer to my question in the post below this one (Thanks to those that helped out --> you know who you are).
"It seems that in PHP when you copy an array with the assignment operator, it does a shallow copy. A shallow copy in simple terms means that references are not dereferenced. The references are copied as well."
So basically this means, for any referenced arrays, you can not do this:
<?php
// Assuming Both Variables Are Arrays.
$new = old;
?>
Because like pointed out, the references will be copied as well.
In the situation of the function that 'matti at withoutthis dot keller dot com' created, look for it 6 posts down, you would need to manually copy the $result array if you fetch your data in a WHILE LOOP, which will always be the case if your result set has more than one row.
To create a copy of the $result array, you will need to do a deep copy to force PHP to dereference all elements. In short, it means you have to manually loop through each element and copy it.
I wrote a quick function, actually its quite easy, that does this for you and has support for multi-dimensional arrays:
<?php
function deepCopy( $source )
{
// Define Local Variable(s).
$final = array( ); // Final Array --> Will House Copied Elements.
$i = 0; // Counter For Loop.
$sourceCount = count( $source ); // Number Of Elements In Source Array.
$sourceKey = array_keys( $source ); // Index Keys For Each Element.
/**
* Loop Through Each Element.
*
* Notice that in the loop through each element, instead of using the loop counter as an index for each element, a call to the
* variable $sourceKey[ $i ] is made instead.
*
* This is to offer support for elements that have their index as a string and not an integer. Remember that $sourceKey is an array
* that houses the original element index values, whether they are strings or integers. So by using the original index value, any
* kind of array will usually work.
*/
for( $i = 0; $i < $sourceCount; $i++ )
{
/**
* Recursive Call.
*
* Sometimes, an element can itself be an Array, thus it too will need to be looped through in order to save all its elements.
* A check is made to see if the element is an array. If it is, a recursive call to this function is made with the element as
* an argument.
*/
if( is_array( $source[ $sourceKey[ $i ] ] ) ) {
$final[ $sourceKey[ $i ] ] = deepCopy( $source[ $sourceKey[ $i ] ] );
}
// Element Is Not An Array --> Save It Normally.
else {
$final[ $sourceKey[ $i ] ] = $source[ $sourceKey[ $i ] ];
}
}
// Return Copied Array.
return $final;
}
?>
Your going to need to use this function if you want to copy an array that has referenced elements without the references included.
Good Luck,
--> Thanks To 'ramirez'`
Michael Newton - http://mike.eire.ca/
13-Feb-2006 11:07
`Windows users:
If you're having problems with this statement in general (not just with DECIMAL columns) try the latest client library from MySQL at http://dev.mysql.com/downloads/connector/php/ to see if it helps.
I couldn't even get the example code above working (using the very latest PHP and MySQL) but swapping in the later DLL files from MySQL fixed everything up.`
andrey at php dot net
30-Nov-2005 02:49
`[ATTENTION] When connecting with 4.1.x libmysql (on windows there is no other option) to 5.0 (5.1) MySQL server there is incompatibility in the protocol regarding type DECIMAL. Therefore result binding on decimal column is not possible. In this case normal mysqli_query() has to be used!!!
When trying to bind you will get FALSE if one of the columns is DECIMAL.`
thejkwhosaysni at gmail dot com
19-Oct-2005 01:12
`I've created these functions which will act like mysqli_fetch_array() and mysqli_fetch_object() but work with bound results.
<?
function fetch_object() {
$data = mysqli_stmt_result_metadata($this->stmt);
$count = 1; //start the count from 1. First value has to be a reference to stmt.
$fieldnames[0] = &$this->stmt;
$obj = new stdClass;
while ($field = mysqli_fetch_field($data)) {
$fn = $field->name; //get all the feild names
$fieldnames[$count] = &$obj->$fn; //load the fieldnames into an object..
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
mysqli_stmt_fetch($this->stmt);
return $obj;
}
function fetch_array() {
$data = mysqli_stmt_result_metadata($this->stmt);
$count = 1; //start the count from 1. First value has to be a reference to the stmt. because bind_param requires the link to $stmt as the first param.
$fieldnames[0] = &$this->stmt;
while ($field = mysqli_fetch_field($data)) {
$fieldnames[$count] = &$array[$field->name]; //load the fieldnames into an array.
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
mysqli_stmt_fetch($this->stmt);
return $array;
}
?>
Hope this helps some people, I was puzzled by this for a while.`
andrey at php dot net
07-Oct-2005 05:38
`If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used
1)prepare()
2)execute()
3)store_result()
4)bind_result()
If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.`
matti at withoutthis dot keller dot com
25-Jul-2005 07:30
`Hi
I saw a bit of discussion about using mysqli_stmt_bin_result dynamically, without knowing exactly how many columns will be returned.
After a while i developed this snippet to mimic the same behaviour as mysql_fetch_array():
<?php
# of fields in result set.
$nof = mysqli_num_fields( mysqli_stmt_result_metadata($handle) );
# The metadata of all fields
$fieldMeta = mysqli_fetch_fields( mysqli_stmt_result_metadata($handle) );
# convert it to a normal array just containing the field names
$fields = array();
for($i=0; $i < $nof; $i++)
$fields[$i] = $fieldMeta[$i]->name;
# The idea is to get an array with the result values just as in mysql_fetch_assoc();
# But we have to use call_user_func_array to pass the right number of args ($nof+1)
# So we create an array:
# array( $stmt, &$result[0], &$result[1], ... )
# So we get the right values in $result in the end!
# Prepare $result and $arg (which will be passed to bind_result)
$result = array();
$arg = array($this->stmt);
for ($i=0; $i < $nof; $i++) {
$result[$i] = '';
$arg[$i+1] = &$result[$i];
}
call_user_func_array ('mysqli_stmt_bind_result',$arg);
# after mysqli_stmt_fetch(), our result array is filled just perfectly,
# but it is numbered (like in mysql_fetch_array() ), not indexed by field name!
# If you just want to mimic that ones behaviour you can stop here :)
mysqli_stmt_fetch($this->stmt);
# Now you can use $result
print_r($result);
# But beware! when using the fetch in a loop, always COPY $result or else you might
# end with all the same values because of the references
?>
Hope that this will help someone....
Matt`
brad dot jackson at resiideo dot com
22-Mar-2005 09:10
`A potential problem exists in binding result parameters from a prepared statement which reference large datatypes like mediumblobs. One of our database tables contains a table of binary image data. Our largest image in this table is around 50Kb, but even so the column is typed as a mediumblob to allow for files larger than 64Kb. I spent a frustrating hour trying to figure out why mysqli_stmt_bind_result choked while trying to allocate 16MB of memory for what should have been at most a 50Kb result, until I realized the function is checking the column type first to find out how big a result _might_ be retrieved, and attempting to allocate that much memory to contain it. My solution was to use a more basic mysqli_result() query. Another option might have been to retype the image data column as blob (64Kb limit).`
add a note
mysqli_stmt_close mysqli_stmt_bind_param

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 10:36:09 2007 PST