You can use prepared statements on stored procedures.
You just need to flush all the subsequent result sets before closing the statement... so:
$mysqli_stmt = $mysqli->prepare(....);
... bind, execute, bind, fetch ...
while($mysqli->more_results())
{
$mysqli->next_result();
$discard = $mysqli->store_result();
}
$mysqli_stmt->close();
Hope that helps :o)
mysqli::multi_query
mysqli_multi_query
(PHP 5)
mysqli::multi_query -- mysqli_multi_query — Exécute une requête MySQL multiple
Description
Style orienté objet :
Style procédural :
Exécute une ou plusieurs requêtes, rassemblées dans le paramètre query par des points-virgules.
Pour lire les résultats de la première requête, vous pouvez utiliser les fonctions mysqli_use_result() et mysqli_store_result(). Tous les autres résultats de requêtes peuvent être atteints avec mysqli_more_results() et mysqli_next_result().
Liste de paramètres
- link
-
Seulement en style procédural : Un identifiant de lien retourné par la fonction mysqli_connect() ou par la fonction mysqli_init()
- query
-
La requête, sous la forme d'une chaîne de caractères.
Valeurs de retour
Retourne FALSE uniquement si la première requête échoue. Pour récupérer les sous-séquences d'erreurs issues des autres requêtes, vous devez appeler d'abord la fonction mysqli_next_result().
Exemples
Exemple #1 Style orienté objet
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Vérification de la connexion */
if (mysqli_connect_errno()) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* Exécution d'une requête multiple */
if ($mysqli->multi_query($query)) {
do {
/* Stockage du premier résultat */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* Affichage d'une séparation */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* Fermeture de la connexion */
$mysqli->close();
?>
Exemple #2 Style procédural
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Vérification de la connexion */
if (mysqli_connect_errno()) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* Exécution d'une requête multiple */
if (mysqli_multi_query($link, $query)) {
do {
/* sStockage du premier résultat */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* Affichage d'une séparation */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
/* Fermeture de la connexion */
mysqli_close($link);
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer
Voir aussi
- mysqli_use_result() - Initialise la récupération d'un jeu de résultats
- mysqli_store_result() - Transfère un jeu de résultats à partir de la dernière requête
- mysqli_next_result() - Prépare le prochain résultat d'une requête multiple
- mysqli_more_results() - Vérifie s'il y a d'autres jeux de résultats MySQL disponibles
mysqli::multi_query
22-Jun-2009 05:47
29-Jan-2009 06:56
This is my point of view:
Actually when calling $mysqli->next_result(), MySQL server will try to prepare resources for storing resultset. If you want to multi query for stored procedures, it's better to use $mysqli->use_result()->close() to close the resources. For functions, it's better to use $mysqli->store_result()->free() since there's resultset returned. Otherwise, an error of "Commands out of sync" will be rasied.
Here's the code I test:
<?php
$mysql = new mysql('localhost', 'user', 'pw', 'db');
$query = 'show tables;';
$query.= 'show tables;';
$query.= 'select * from dummy_table;';
$query.= 'show tables;'; // this statement will be ignored as the dummy_table doesn't exist and the loop should quit
$mysqli->multi_query($query);
do {
$mysqli->use_result()->close();
echo "Okay\n";
} while ($mysqli->next_result());
if ($mysqli->errno) {
echo "Stopped while retrieving result : ".$mysqli->error;
}
?>
Returns :
Okay
Okay
Stopped while retrieving result : Table 'db.dummy_table' doesn't exist
27-Aug-2008 04:05
It's very important that after executing mysqli_multi_query you have first process the resultsets before sending any another statement to the server, otherwise your
socket is still blocked.
Please note that even if your multi statement doesn't contain SELECT queries, the server will send result packages containing errorcodes (or OK packet) for single statements.
04-Mar-2008 12:13
mysqli_multi_query handles MySQL Transaction on InnoDB's :-)
<?php
$mysqli = mysqli_connect( "localhost", "owner", "pass", "db", 3306, "/var/lib/mysql/mysql.sock" );
$QUERY = <<<EOT
START TRANSACTION;
SELECT @lng:=IF( STRCMP(`main_lang`,'de'), 'en', 'de' )
FROM `main_data` WHERE ( `main_activ` LIKE 1 ) ORDER BY `main_id` ASC;
SELECT `main_id`, `main_type`, `main_title`, `main_body`, `main_modified`, `main_posted`
FROM `main_data`
WHERE ( `main_type` RLIKE "news|about" AND `main_lang` LIKE @lng AND `main_activ` LIKE 1 )
ORDER BY `main_type` ASC;
COMMIT;
EOT;
$query = mysqli_multi_query( $mysqli, $QUERY ) or die( mysqli_error( $mysqli ) );
if( $query )
{
do {
if( $result = mysqli_store_result( $mysqli ) )
{
$subresult = mysqli_fetch_assoc( $result );
if( ! isset( $subresult['main_id'] ) )
continue;
foreach( $subresult AS $k => $v )
{
var_dump( $k , $v );
}
}
} while ( mysqli_next_result( $mysqli ) );
}
mysqli_close( $mysqli );
?>
30-Nov-2006 06:47
I was developing my own CMS and I was having problem with attaching the database' sql file. I thought mysqli_multi_query got bugs where it crashes my MySQL server. I tried to report the bug but it showed that it has duplicate bug reports of other developers. To my surprise, mysqli_multi_query needs to bother with result even if there's none.
I finally got it working when I copied the sample and removed somethings. Here is what it looked liked
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CREATE TABLE....;...;... blah blah blah;...";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
//do nothing since there's nothing to handle
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
//I just kept this since it seems useful
//try removing and see for yourself
}
} while (mysqli_next_result($link));
}
/* close connection */
mysqli_close($link);
?>
bottom-line: I think mysql_multi_query should only be used for attaching a database. it's hard to handle results from 'SELECT' statements inside a single while loop.
08-Sep-2006 12:32
Ive just had exactly the same problem as below trying to execute multiple stored procedures. I thought i might as well add how to do it the object oriented way.
Instead of putting the one statement:
<?php
$mysqli->next_result();
?>
Put two:
<?php
$mysqli->next_result();
$mysqli->next_result();
?>
The first statement points (possibly using the term incorrectly) you to the return value. The second one will point you to the result of the next query.
I hope this makes sense.
08-May-2006 11:02
Note that you need to use this function to call Stored Procedures!
If you experience "lost connection to MySQL server" errors with your Stored Procedure calls then you did not fetch the 'OK' (or 'ERR') message, which is a second result-set from a Stored Procedure call. You have to fetch that result to have no problems with subsequent queries.
Bad example, will FAIL now and then on subsequent calls:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
$this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);
?>
Working example:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
$this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);
if(mysqli_more_results($this->sqlLink))
while(mysqli_next_result($this->sqlLink));
?>
Of course you can do more with the multiple results then just throwing them away, but for most this will suffice. You could for example make an "sp" function which will kill the 2nd 'ok' result.
This nasty 'OK'-message made me spend hours trying to figure out why MySQL server was logging warnings with 'bad packets from client' and PHP mysql_error() with 'Connection lost'. It's a shame the mysqli library does catch this by just doing it for you.
