mysqli::store_result

mysqli_store_result

(PHP 5, PHP 7, PHP 8)

mysqli::store_result -- mysqli_store_resultTransfiere un conjunto de resultados desde la última consulta

Descripción

Estilo orientado a objetos

public mysqli::store_result(int $mode = 0): mysqli_result|false

Estilo por procedimientos

mysqli_store_result(mysqli $mysql, int $mode = 0): mysqli_result|false

Transfiere el conjunto de resultados desde la última consulta en la conexión a la base de datos especificada por el argumento mysql para su uso con mysqli_data_seek().

Parámetros

link

Sólo estilo por procediminetos: Un identificador de enlace devuelto por mysqli_connect() o mysqli_init()

mode

La opción que se desea definir. A partir de PHP 8.1, este argumento no tiene ningún efecto. Puede tomar uno de los siguientes valores:

Opciones válidas
Nombre Descripción
MYSQLI_STORE_RESULT_COPY_DATA Copia los resultados recuperados de un buffer interno mysqlnd a variables PHP. Por omisión, mysqlnd utilizará una referencia lógica para evitar la copia y la duplicación de los resultados contenidos en memoria. Para ciertos conjuntos de resultados, por ejemplo, los conjuntos de resultados con muchas filas pequeñas, el enfoque de copia puede reducir el uso de memoria por las variables PHP que contienen los resultados pueden ser liberadas rápidamente (disponible únicamente con mysqlnd)

Valores devueltos

Retorna un resultado almacenado en forma de objeto o false si ocurre un error.

Nota:

mysqli_store_result() retorna false en caso de que la consulta no retorne un conjunto de resultados (si la consulta es de tipo INSERT por ejemplo). Esta función retornará siempre false si el conjunto de resultados no puede ser leído. Se puede saber si hay un error utilizando la función mysqli_error() y mirando si retorna un string vacío, o si mysqli_errno() retorna cero, o bien si mysqli_field_count() retorna un valor diferente de cero. Otra razón para que esta función retorne false es que el conjunto de resultados retornado después de una consulta exitosa llamada por mysqli_query() es demasiado largo (la memoria para este no puede ser asignada). Si mysqli_field_count() retorna un valor diferente de cero, el procesamiento debería producir un conjunto de resultados no vacío.

Errores/Excepciones

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

Historial de cambios

Versión Descripción
8.4.0 El paso del argumento mode está ahora obsoleto. Este argumento no ha tenido ningún efecto desde PHP 8.1.0.

Ejemplos

Ver la función mysqli_multi_query().

Notas

Nota:

Siempre se recomienda liberar la memoria asignada para el resultado utilizando la función mysqli_free_result(), al transferir grandes resultados utilizando la función mysqli_store_result() esto se vuelve particularmente importante.

Ver también

add a note

User Contributed Notes 4 notes

up
11
mitchind
15 years ago
After reading through original notes and example above as well as wading through the documentation, I finally got a loop to work with two stored procedures.

Using the results of the first one as a parameter for the second one. Easier to do this way than a huge modified sequence of Inner Join queries.

Hope this helps others...

<?php
// Connect to server and database
$mysqli = new mysqli("$dbServer", "$dbUser", "$dbPass", "$dbName");

// Open First Stored Procedure using MYSQLI_STORE_RESULT to retain for looping
$resultPicks = $mysqli->query("CALL $proc ($searchDate, $maxRSI, $incRSI, $minMACD, $minVol, $minTrades, $minClose, $maxClose)", MYSQLI_STORE_RESULT);

// process one row at a time from first SP
while($picksRow = $resultPicks->fetch_array(MYSQLI_ASSOC)) {
// Get Parameter for next SP
$symbol = $picksRow['Symbol'];

// Free stored results
clearStoredResults($mysqli);

// Execute second SP using value from first as a parameter (MYSQLI_USE_RESULT and free result right away)
$resultData = $mysqli->query("CALL prcGetLastMACDDatesBelowZero('$symbol', $searchDate)", MYSQLI_USE_RESULT);
$dataRow = $resultData->fetch_array(MYSQLI_ASSOC);

// Dump result from both related queries
echo "<p>$symbol ... Num Dates: " . $dataRow['NumDates'];

// Free results from second SP
$resultData->free();

}

// Free results from first SP
$resultPicks->free();

// close connections
$mysqli->close();

#------------------------------------------
function clearStoredResults($mysqli_link){
#------------------------------------------
while($mysqli_link->next_result()){
if(
$l_result = $mysqli_link->store_result()){
$l_result->free();
}
}
}
?>
up
2
filippo at ecoms dot it
7 years ago
Code to handling errors:

if ($mysqli->multi_query($query)) {
$result = $mysqli->store_result();
if ($mysqli->errno == 0) {

/* First result set or FALSE (if the query didn't return a result set) is stored in $result */

while ($mysqli->more_results()) {
if ($mysqli->next_result()) {
$result = $mysqli->store_result();
if ($mysqli->errno == 0) {
/* The result set or FALSE (see above) is stored in $result */
}
else {
/* Result set read error */
break;
}
}
else {
/* Error in the query */
}
}
}
else {
/* First result set read error */
}
}
else {
/* Error in the first query */
}
up
-4
Warner
15 years ago
It also seems, that executing a SET statement in multi_query() returns an extra recordset too, which one would not expect.
up
-4
lau at goldenweb dot com dot au
18 years ago
Beware when using stored procedures:
If you connect to the database and then call dbproc A followed by a call to db proc B and then close the connection to the db, the second procedure call will not work.

It looks like there is a bug in MYSQL or mysqli that returns an extra recordset than you would expect. It then doesn't let you call another stored procedure until you finish processing all the recordsets from the first stored procedure call.

The solution is to simply loop through the additional recordsets between calls to db procs. Here is a function that I call between db proc calls:

<?php
#--------------------------------
function ClearRecordsets($p_Result){
#--------------------------------
$p_Result->free();
while(
$this->Mysqli->next_result()){
if(
$l_result = $this->Mysqli->store_result()){
$l_result->free();
}
}
}

?>
To Top