mysqli_stmt_bind_result> <mysqli_stmt_attr_set
Last updated: Mon, 28 Dec 2009

mysqli_stmt_bind_param

stmt->bind_param()

(No version information available, might be only in CVS)

stmt->bind_param() — Binds variables to a prepared statement as parameters

Descrição

Procedural style:

bool mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Object oriented style (method):

mysqli_stmt
bool bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare().

Nota: If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

Parâmetros

stmt

Apenas para estilo de procedimento: Um identificador de statement retornado por mysqli_stmt_init().

types

A string that contains one or more characters which specify the types for the corresponding bind variables:

Type specification chars
Character Description
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets

var1

The number of variables and length of string types must match the parameters in the statement.

Valor Retornado

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplos

Example#1 Object oriented style

<?php
$mysqli 
= new mysqli('localhost''my_user''my_password''world');

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

$stmt $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd'$code$language$official$percent);

$code 'DEU';
$language 'Bavarian';
$official "F";
$percent 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n"$stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n"$mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Example#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();
}

$stmt mysqli_prepare($link"INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt'sssd'$code$language$official$percent);

$code 'DEU';
$language 'Bavarian';
$official "F";
$percent 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n"mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link"DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n"mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?>

O exemplo acima irá imprimir:

1 Row inserted.
1 Row deleted.


mysqli_stmt_bind_result> <mysqli_stmt_attr_set
Last updated: Mon, 28 Dec 2009
 
User Contributed Notes
mysqli_stmt_bind_param
michael dot martinek at gmail dot com
30-Dec-2007 11:00
Small correction. This version removes the NULL element from the array, so it doesn't fall on to the next ? when passed to mysql_stmt_bind_param(). Note that $saParams is still passed by reference, but now it is being modified.

<?php

function preparse_prepared($sQuery, &$saParams)
{
   
$nPos = 0;

   
$sRetval = $sQuery;
    foreach (
$saParams as $x_Key => $Param)
    {
       
//if we find no more ?'s we're done then
       
if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
        {
            break;
        }

       
//this test must be done second, because we need to increment offsets of $nPos for each ?.
        //we have no need to parse anything that isn't NULL.
       
if (!is_null($Param))
        {
            continue;
        }

               
       
//null value, replace this ? with NULL.
       
$sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);

       
//unset this element now
       
unset($saParams[$x_Key]);
    }
           
           
    return
$sRetval;
}

?>
michael dot martinek at gmail dot com
30-Dec-2007 10:52
I've found that you can't pass NULL values in using mysql_stmt_bind_param. Recently I ran into this problem because I wrote some MySQL routines that would update existing data, but only when the value wasn't NULL.

My solution to work around this is simple:

<?php

function preparse_prepared($sQuery, &$saParams)
{
   
$nPos = 0;

   
$sRetval = $sQuery;
    foreach (
$saParams as $Param)
    {
       
//if we find no more ?'s we're done then
       
if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
        {
            break;
        }

       
//this test must be done second, because we need to increment offsets of $nPos for each ?.
        //we have no need to parse anything that isn't NULL.
       
if (!is_null($Param))
        {
            continue;
        }

               
       
//null value, replace this ? with NULL.
       
$sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);
    }
           
           
    return
$sRetval;
}

?>

This will iterate the given list of parameters and replace any null values in the query with an actual null value. You'll want to use the resulting $sQuery to pass to mysqli_prepare(). For that, I use another routine that generates a list of the values (s, i, etc).

For example:

<?php

                    array_unshift
($saParams, $this->getPreparedTypeString($saParams));
                   
array_unshift($saParams, $stmt);
                   
                   
call_user_func_array('mysqli_stmt_bind_param', $saParams);

?>

Where getPreparedTypeString is defined as:

<?php

       
public static function getPreparedTypeString(&$saParams)
        {
           
$sRetval = '';

           
//if not an array, or empty.. return empty string
           
if (!is_array($saParams) || !count($saParams))
            {
                return
$sRetval;
            }

           
//iterate the elements and figure out what they are, and append to result
           
foreach ($saParams as $Param)
            {
                if (
is_int($Param))
                {
                   
$sRetval .= 'i';
                }
                else if (
is_double($Param))
                {
                   
$sRetval .= 'd';
                }
                else if (
is_string($Param))
                {
                   
$sRetval .= 's';
                }
            }

            return
$sRetval;
        }

?>

To clarify why I pass array values by reference: They aren't being modified, so I don't want copies of them begin made in memory as they may be large. In other languages, this is much more efficient. Not sure if PHP handles passing values on a "copy on edit" basis.. but I'm guessing not.
Anonymous
15-Dec-2007 04:24
It's worth noting that you have to bind all parameters in one fell swoop - you can't go through and call bind_param once for each.
evangun2001 at yahoo dot fr
19-Sep-2007 08:30
About the previous message :
I don't know if it has been fixed or if it always worked, but binding parameters only once works (almost) fine.
Just mind the bug (current version: 5.2.4) I describe here : http://bugs.php.net/bug.php?id=42689
usera at example dot com
20-Jul-2007 12:50
Some examples in the documentation suggest that you can call $stmt->bind_param() once, then call $stmt->execute() several times while altering the bound variables each time, so as to e.g. insert several records into a data base. This is not true.

You need to call $stmt->bind_param() once each time AFTER you altered the set of variables, and BEFORE you call $stmt->execute()

This may be a bug. If it is not, the documentation is flawed, and there is no gain to the programmer using the new mysqli interface at this point.
mixleplix1 at yahoo dot com
19-Jun-2007 05:12
To continue on previous post
Bigints and the 'd' type:

If the digit you insert is longer then 16 digits the last digits will alter. I was noticing this in my inserts.

1111111111111111111 changes to 1111111111111111168

I had to switch to using 's' as type
flame
19-Feb-2007 02:44
Columns with type bigint need to be specified as type 'd' NOT 'i'.

Using 'i' results in large numbers (eg 3000169151) being truncated.

--
flame

mysqli_stmt_bind_result> <mysqli_stmt_attr_set
Last updated: Mon, 28 Dec 2009