I recently tried the use of inserts using multi_query()
and sometimes the code failed.
When using multi_query()
we must take into account the type of data we are trying to insert.
Suppose this insertion string:
$query="INSERT INTO tabla (columna_int,columna_str) VALUES ($i,$str);";
To send this string by multi_query()
and not have an error, it is necessary to enclose in single quotes all the variables that contain values of the string type , in the case of the example: '$str'
For variables that are integers, it is not necessary. But there is something that we sometimes fail with the integers, if $int
is destined to a column of type entero
of our database, the correct thing is to send it converted in whole, and without enclosing in single quotes. If we want we can send it as a string, maybe it works, but is not correct .
Note also that we should start and end the SQL statement with double quotes ( "
) , so there is no conflict with the single quotes inside the SQL string.
Also the PHP Manual (see link at the end) says that multi_query
:
Execute one or multiple queries concatenated by semicolons .
Therefore, each query must end with a semicolon ( ;
) .
Then the $query
would look like this:
$query="INSERT INTO tabla (columna_int,columna_str) VALUES ($i,'$str');";
You also have to use properly: next_result()
and more_results()
.
The Manual says that:
To obtain the result set of the first consultation, you can
use mysqli_use_result()
or mysqli_store_result()
. The rest of
Query results can be obtained using mysqli_more_results()
and mysqli_next_result()
.
Proven and functional example code:
<?php
$query="INSERT INTO tabla (columna_int,columna_str) VALUES ($i,'$str');";
// Ejecutar SQL
$i = 0;
if( $this->mysqli->multi_query( $query ) )
{
do {
$this->mysqli->next_result();
$i++;
}
while( $this->mysqli->more_results() );
}
if( $this->mysqli->errno )
{
die(
'<h1>ERROR</h1>
Consulta #' . ( $i + 1 ) . '</pre><br /><br />
<span style="color:red;">' . $this->mysqli->error . '</span>'
);
}
?>