CakeFest 2024: The Official CakePHP Conference

mysqli::store_result

mysqli_store_result

(PHP 5, PHP 7, PHP 8)

mysqli::store_result -- mysqli_store_resultTransfere um conjunto de resultados da última consulta

Descrição

Estilo orientado a objetos

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

Estilo procedural

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

Transfere o conjunto de resultados da última consulta na conexão do banco de dados representada pelo parâmetro mysql para ser usado com a função mysqli_data_seek().

Parâmetros

mysql

Somente no estilo procedural: Um objeto mysqli retornado por mysqli_connect() ou mysqli_init()

mode

A opção que você deseja definir. A partir do PHP 8.1, este parâmetro não tem efeito. Pode ser um dos seguintes valores:

Valid options
Nome Descrição
MYSQLI_STORE_RESULT_COPY_DATA Copia os resultados do buffer mysqlnd interno nas variáveis PHP buscadas. Por padrão, o mysqlnd usará uma lógica de referência para evitar copiar e duplicar os resultados mantidos na memória. Para certos conjuntos de resultados, por exemplo, conjuntos de resultados com muitas linhas pequenas, a abordagem de cópia pode reduzir o uso geral de memória porque as variáveis PHP que contêm resultados podem ser liberadas mais cedo (disponível apenas com mysqlnd)

Valor Retornado

Retorna um objeto de resultado armazenado em buffer ou false se ocorreu um erro.

Nota:

mysqli_store_result() retorna false caso a consulta não retorne um conjunto de resultados (se a consulta for, por exemplo, uma instrução INSERT). Esta função também retorna false se a leitura do conjunto de resultados falhou. Você pode verificar se houve um erro verificando se mysqli_error() não retorna uma string vazia, se mysqli_errno() retorna um valor diferente de zero ou se mysqli_field_count() retorna um valor diferente de zero. Além disso, a possível razão para esta função retornar false após uma chamada bem-sucedida para mysqli_query() pode ser um conjunto de resultados muito grande (a memória para ele não pode ser alocada). Se mysqli_field_count() retornar um valor diferente de zero, a instrução deve ter produzido um conjunto de resultados não vazio.

Erros/Exceções

Se o relatório de erros da extensão mysqli estiver habilitado (MYSQLI_REPORT_ERROR) e a operação solicitada falhar, um aviso será gerado. Se, além disso, o modo for definido como MYSQLI_REPORT_STRICT, uma exceção mysqli_sql_exception será lançada em vez do aviso.

Exemplos

Veja mysqli_multi_query().

Notas

Nota:

Embora seja sempre uma boa prática liberar a memória usada pelo resultado de uma consulta usando a função mysqli_free_result(), ao transferir grandes conjuntos de resultados usando mysqli_store_result() isso se torna particularmente importante.

Veja Também

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