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

search for in the

mysqli_stmt::reset> <mysqli_stmt->param_count
Last updated: Fri, 05 Dec 2008

view this page in

mysqli_stmt::prepare

mysqli_stmt_prepare

(PHP 5)

mysqli_stmt::prepare -- mysqli_stmt_preparePrépare une requête SQL pour l'exécution

Description

Style orienté objet (méthode) :

mixed mysqli_stmt::prepare ( string $query )

Style procédural :

bool mysqli_stmt_prepare ( mysqli_stmt $stmt , string $query )

Prépare la requête SQL query , pour la session de travail stmt .

Les variables SQL doivent être associées à une variable PHP à l'aide de la fonction mysqli_stmt_bind_param() et/ou mysqli_stmt_bind_result(), avant d'exécuter la requête.

Liste de paramètres

stmt

Style procédural uniquement : Un identifiant de requête retourné par la fonction mysqli_stmt_init().

query

La requête, sous forme de chaîne. Elle doit être constituée d'une commande SQL valide et unique.

Ce paramètre peut inclure une ou plusieurs variables SQL, en utilisant des points d'interrogation (?) aux bons endroits.

Note: Il ne faut pas ajouter de point-virgule ou de \g à la fin de la requête.

Note: Les variables SQL ne sont possibles que dans certaines clauses de la requête SQL. Par exemple, elles peuvent être placées dans des clause VALUES() d'une requête INSERT (pour spécifier une valeur à insérer), ou dans une clause de condition WHERE.
Cependant, elles ne sont pas autorisées pour les identifiants (de tables ou de colonnes), dans les listes de colonnes d'un SELECT, ou pour spécifier des opérateurs comme =. Cette dernière restriction est liée au fait qu'il est impossible de déterminer le type. En général, les variables SQL ne sont valides que dans les commandes de manipulation de données ("Data Manipulation Language" (DML)), et non dans les structures du langages SQL ("Data Definition Language" (DDL)).

Valeurs de retour

Cette fonction retourne TRUE en cas de succès, FALSE en cas d'échec.

Exemples

Exemple #1 Style orienté objet

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

/* Vérifie la connexion */
if (mysqli_connect_errno()) {
    
printf("Échec de la connexion : %s\n"mysqli_connect_error());
    exit();
}

$city "Amersfoort";

/* Création d'une requête préparée */
$stmt =  $mysqli->stmt_init();
if (
$stmt->prepare("SELECT District FROM City WHERE Name=?")) {

    
/* Association des variables SQL */
    
$stmt->bind_param("s"$city);

    
/* Exécution de la requête */
    
$stmt->execute();

    
/* Association des variables de résultats */
    
$stmt->bind_result($district);

    
/* Lecture des valeurs */
    
$stmt->fetch();

    
printf("%s est dans la région de %s\n"$city$district);

    
/* Fermeture de la commande */
    
$stmt->close();
}

/* Fermeture de la connexion */
$mysqli->close();
?>

Exemple #2 Style procédural

<?php
$link 
mysqli_connect("localhost""my_user""my_password""world");

/* Vérifie la connexion */
if (mysqli_connect_errno()) {
    
printf("Échec de la connexion : %s\n"mysqli_connect_error());
    exit();
}

$city "Amersfoort";

/* Création d'une requête préparée */
$stmt mysqli_stmt_init($link);
if (
mysqli_stmt_prepare($stmt'SELECT District FROM City WHERE Name=?')) {

    
/* Association des variables SQL */
    
mysqli_stmt_bind_param($stmt"s"$city);

    
/* Exécution de la requête */
    
mysqli_stmt_execute($stmt);

    
/* Association des variables de résultats */
    
mysqli_stmt_bind_result($stmt$district);

    
/* Lecture des valeurs */
    
mysqli_stmt_fetch($stmt);

    
printf("%s est dans la région de %s\n"$city$district);

    
/* Fermeture de la commande */
    
mysqli_stmt_close($stmt);
}

/* Fermeture de la connexion */
mysqli_close($link);
?>

L'exemple ci-dessus va afficher :

Amersfoort est dans la région de Utrecht


mysqli_stmt::reset> <mysqli_stmt->param_count
Last updated: Fri, 05 Dec 2008
 
add a note add a note User Contributed Notes
mysqli_stmt::prepare
kontakt at arthur minus schiwon dot de
16-Jun-2008 07:22
If you wrap the placeholders with quotation marks you will experience warnings like "Number of variables doesn't match number of parameters in prepared statement" (at least with INSERT Statements).
mhradek AT gmail.com
15-May-2008 04:06
A particularly helpful adaptation of this function and the call_user_func_array function:

// $params is sent as array($val=>'i', $val=>'d', etc...)

function db_stmt_bind_params($stmt, $params)
{
    $funcArg[] = $stmt;
    foreach($params as $val=>$type)
    {
        $funcArg['type'] .= $type;
        $funcArg[] = $val;
    }
    return call_user_func_array('mysqli_stmt_bind_param', $funcArgs);
}

Thanks to 'sned' for the code.
lukaszNOSPAMPLEASE at epas dot pl
15-Jan-2008 07:15
i've got some bad news for you guys if you haven't found out already.
the trick with mysqli_next_result() only prevents having the connection dropped after a stored procedure call.
apparently you can bind parameters for a prepared stored procedure call, but you'll get messed up records from mysqli_stmt_fetch() after mysqli_stmt_bind_result(), at least when the stored procedure itself contains a prepared statement.
a way to avoid data corruption could be specifying the CLIENT_MULTI_STATEMENTS flag in mysqli_real_connect(), if it wasn't disabled entirely (for security reasons, as they say). another option is to use mysqli_multi_query(), but then you can't bind at all.
st dot john dot johnson at gmail dot com
04-Jun-2007 08:59
In reference to what lachlan76 said before, stored procedures CAN be executed through prepared statements as long as you tell the DB to move to the next result before executing again.

Example (Five calls to a stored procedure):

<?php
for ($i=0;$i<5;$i++) {
 
$statement = $mysqli->stmt_init();
 
$statement->prepare("CALL some_procedure( ? )");

 
// Bind, execute, and bind.
 
$statement->bind_param("i", 1);
 
$statement->execute();
 
$statement->bind_result($results);

  while(
$statement->fetch()) {
   
// Do what you want with your results.
 
}

 
$statement->close();

 
// Now move the mysqli connection to a new result.
 
while($mysqli->next_result()) { }
}
?>

If you include the last statement, this code should execute without the nasty "Commands out of sync" error.
lachlan76 at gmail dot com
28-Nov-2006 08:59
Do not try to use a stored procedure through a prepared statement.

Example:

<?php
$statement
= $mysqli->stmt_init();
$statement->prepare("CALL some_procedure()");
?>

If you attempt to do this, it will fail by dropping the connection during the next query.  Use mysqli_multi_query instead.

Example:

<?php
$mysqli
->multi_query("CALL some_procedure()");
do
{
 
$result = $mysqli->store_result();

  
// Do your processing work here 
 
 
$result->free();
} while(
$mysqli->next_result());
?>

This means that you cannot bind parameters or results, however.
andrey at php dot net
07-Oct-2005 05:35
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.

mysqli_stmt::reset> <mysqli_stmt->param_count
Last updated: Fri, 05 Dec 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites