PHP 8.3.4 Released!

mysqli::store_result

mysqli_store_result

(PHP 5, PHP 7, PHP 8)

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

Descripción

Estilo orientado a objetos

mysqli::store_result(int $option = ?): mysqli_result

Estilo por procedimientos

mysqli_store_result(mysqli $link, int $option = ?): mysqli_result

Transfiere el conjunto de resultados de la última consulta de la conexión a la base de datos representada por el parámetro link a ser usado con la función mysqli_data_seek().

Parámetros

link

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

option

La opción a establecer. Puede ser uno de los siguientes valores:

Opciones válidas
Nombre Descripción
MYSQLI_STORE_RESULT_COPY_DATA Copiar los resultados desde el búfer interno de mysqlnd a variables de PHP. Por defecto, mysqlnd usará un lógica de referencia para evitar copiar y duplicar resultados contenidos en memoria. Para ciertos conjuntos de resultados con filas muy pequeñas, por ejemplo, la estrategia de copia puede reducir el uso total de memoria debido a que las variables de PHP de contienen resultados podrían ser liberadas antes (disponible con mysqlnd solamente, desde PHP 5.6.0)

Valores devueltos

Devuelve un objeto de resultados almacenado en buffer o false si ocurrió un error.

Nota:

mysqli_store_result() devuelve false en caso de que la consulta no devuelve un conjunto de resultados (si la consulta era, por ejemplo, una sentencia INSERT). Esta función también devuelve false si la lectura del conjunto de resultados falla. Se puede comprobar si se ha obtenido un error comprobando si mysqli_error() no devuelve una cadena vacía, si mysqli_errno() devuelve un valor distinto de cero, o si mysqli_field_count() devuelve un valor distinto de cero. Otra posible razón para que esta función devuelva false después de una llamada con éxito a mysqli_query() puede ser un conjunto de resultados demasiado grande (no es posible asignarle memoria). Si mysqli_field_count() devuelve un valor distinto de cero, la sentencia debería haber producido un conjunto de resultados no vacío.

Notas

Nota:

Aunque es una buena práctica liberar la memoria usada por los resultados de una consulta usando la función mysqli_free_result(), al transferir conjuntos de resultados grandes usando la función mysqli_store_result() esto se convierte en particularmente importante.

Ejemplos

Véase mysqli_multi_query().

Ver también

add a note

User Contributed Notes 5 notes

up
10
mitchind
14 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
6 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
-3
Warner
14 years ago
It also seems, that executing a SET statement in multi_query() returns an extra recordset too, which one would not expect.
up
-6
Tex Morgan
10 years ago
There's a simpler way to clear out database stored procedure problems:

class MySQLiQuery {
protected $_resultSet;
protected $databaseConnection;
....

protected function free(){
$this->_resultSet->free();
$this->_resultSet=null;
}

protected function checkMoreResults(){
if($this->databaseConnection->more_results()){
return true;
} else {
return false;
}
}

protected function clearResults(){
if($this->checkMoreResults()){
if($this->databaseConnection->next_result()){
if($this->_resultSet=$this->databaseConnection->store_result()){
$this->free();
}
$this->clearResults(); // <----------- recursive call is your friend
}
}
}
.......
}
up
-5
lau at goldenweb dot com dot au
16 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