PHP 8.3.4 Released!

mysqli_stmt::store_result

mysqli_stmt_store_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::store_result -- mysqli_stmt_store_resultСохраняет набор результатов во внутреннем буфере

Описание

Объектно-ориентированный стиль

public mysqli_stmt::store_result(): bool

Процедурный стиль

mysqli_stmt_store_result(mysqli_stmt $statement): bool

Функцию следует вызывать для запросов, которые успешно создают набор результатов (например, SELECT, SHOW, DESCRIBE, EXPLAIN), только если необходимо буферизовать в PHP полный набор результатов. Каждый последующий вызов mysqli_stmt_fetch() будет возвращать буферизованные данные.

Замечание:

В остальных случаях вызывать mysqli_stmt_store_result() нет необходимости. Но если такой вызов совершён, ничего страшного не случится, это не повлияет на производительность и целостность данных. Чтобы убедиться, что запрос вернул результирующий набор, можно воспользоваться функцией mysqli_stmt_result_metadata(), которая в этом случае вернёт false.

Список параметров

stmt

Только для процедурного стиля: объект mysqli_stmt, который вернула функция mysqli_stmt_init().

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае ошибки.

Ошибки

Если уведомления об ошибках mysqli включены (MYSQLI_REPORT_ERROR) и запрошенная операция не удалась, выдаётся предупреждение. Если, кроме того, установлен режим MYSQLI_REPORT_STRICT, вместо этого будет выброшено исключение mysqli_sql_exception.

Примеры

Пример #1 Объектно-ориентированный стиль

<?php

mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();

/* сохранение результата во внутреннем буфере */
$stmt->store_result();

printf("Число строк: %d.\n", $stmt->num_rows);

Пример #2 Процедурный стиль

<?php

mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);

/* сохранение результата во внутреннем буфере */
mysqli_stmt_store_result($stmt);

printf("Число строк: %d.\n", mysqli_stmt_num_rows($stmt));
?>

Результат выполнения приведённых примеров:

Количество строк: 20.

Смотрите также

  • mysqli_prepare() - Подготавливает SQL выражение к выполнению
  • mysqli_stmt_result_metadata() - Возвращает метаданные результирующей таблицы подготавливаемого запроса
  • mysqli_stmt_fetch() - Связывает результаты подготовленного выражения с переменными

add a note

User Contributed Notes 5 notes

up
13
kitlum AT ukr DOT net
8 years ago
Lost some hours to find out how to save multirows result of mysqli_stmt to array, when get_result prohibited.
Idea, which works is using store_result
$stmt=$this->mysqli->prepare("SELECT surname, name, user_id, last_m_own, last_m_str, role FROM users WHERE referer_id=(?)");
$stmt->bind_param('i',$referer_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ans['surname'], $ans['name'], $ans['user_id'], $ans['last_m_own'], $ans['last_m_str'], $ans['role']);
$j=$stmt->num_rows;
for ($i=0;$i<$j;$i++){
$stmt->data_seek($i);
$stmt->fetch();
foreach ($ans as $key=>$value){
$result[$i][$key]=$value;
}
}
Hope will helpful for such newbies as me
up
8
pcc at pccglobal dot com
13 years ago
When using prepare to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch
The following applies to a Windows SBS server running IIS/6.0 + PHP 5.2.1
MySQL server version 5.0.26-community-nt, client version 5.0.51a

<?php
$database
= "test" ;
$table = "test" ;
$column = "flongblob" ;
$mysqli = new mysqli("localhost", "root", "<secret_password>", $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT `$column` FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
// Fetch a record. Bind the result to a variable called 'value' and fetch.
$stmt->bind_result($value) ;
$res = $stmt->fetch() ;
if(
$res)
{
// strlen($value) should have LOB length, not 1 or zero.
echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
echo ((
false !== $res) ? "End of data" : $stmt->error) . "\n" ;
break ;
}
// Fetch another record.
$res = $stmt->fetch() ;
if(
$res)
{
// strlen($value) should have LOB length, not 1 or zero.
echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
echo ((
false !== $res) ? "End of data" : $stmt->error) . "\n" ;
break ;
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
flongblob data length is 932353 bytes.
flongblob data length is 867300 bytes.

If wrong procedure order MySQLi crashes or outputs:
flongblob data length is 0 bytes.
flongblob data length is 867300 bytes.
up
4
neromir at hotmail dot com
15 years ago
The wording above, in the initial description of the function, can be confusing (quoted below).

"You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data. "

I had initially understood the part saying "and only if you want to buffer..." to mean that it was only necessary to call this function if you wanted to buffer the result set. This, however, is not the case, and the misunderstanding caused me quite a bit of grief.

So, to clarify for anyone suffering from the same misunderstanding, you ALWAYS must call this function for every query that produces a result set (as listed in the parentheses of the quote above), as far as I can tell.
up
2
UCFirefly (at) yahoo.com
18 years ago
fetch_fields() does not seem to be compatible with prepared statements like those used here. Makes things difficult if you're using a wildcard. I guess that's better for security in some obscure way.
up
0
Typer85 at gmail dot com
17 years ago
In response to the note below me for the claim that mysqli_fetch_fields is not compatible with prepared statements.

This is untrue, it is but you have to do a little extra work. I would recommend you use a wrapper function of some sort to take care of the dirty business for you but the basic idea is the same.

Let's assume you have a prepared statement like so. I am going to use the procedural way for simplicity but the same idea can be done using the object oriented way:

<?php

// Connect Blah Blah Blah.

$connectionLink = mysqli_connect( .... );

// Query Blab Blah Blah.

$query = "Select `Id` From `Table` Where `Id` = ?";

// Prepare Query.

$prepareObject = mysqli_prepare( $connectionLink , $query );

// Bind Query.

mysqli_stmt_bind_param( $prepareObject , 'i' , 1 );

// Execute Query.

mysqli_stmt_execute( $prepareObject );

?>

Now all the above is fine and dandy to anyone familiar with using prepared statements, but if I want to use mysqli_fetch_fields or any other function that fetches meta information about a result set but does not work on prepared statements?

Enter the special function mysqli_stmt_result_metadata. It can be used as follows, assume the following code segment immediatley follows that of the above code segment.

<?php

$metaData
= mysqli_stmt_result_metadata( $prepareObject );

// I Can Now Call mysqli_fetch_fields using the variable
// $metaData as an argument.

$fieldInfo = mysqli_fetch_fields( $metaData );

// Or Even This.

$fieldInfo = mysqli_num_fields( $metaData );

?>

Take a look at the Manual entry for mysqli_stmt_result_metatdata function for full details on how to expose it with prepared statements.

Good Luck,
To Top