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 memysqli_stmt::store_result
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
mysqli_stmt::store_result
Референца за `mysqli-stmt.store-result.php` со подобрена типографија и навигација.
mysqli_stmt::store_result
mysqli_stmt_store_result
класата mysqli_driver
mysqli_stmt::store_result -- mysqli_stmt_store_result — Чува сет на резултати во внатрешен бафер
= NULL
Напиши целосна ознака на елемент
Процедурален стил
Оваа функција треба да се повика за прашања што успешно произведуваат сет на резултати (на пр. SELECT, SHOW, DESCRIBE, EXPLAIN) само ако целиот сет на резултати треба да се баферира во PHP. Секое следно
mysqli_stmt_fetch() повикување ќе врати баферирани податоци.
Забелешка:
Не е потребно да се повика mysqli_stmt_store_result() за други прашања, но ако го направите, тоа нема да наштети или да предизвика значителна загуба на перформансите во сите случаи. Можете да откриете дали прашањето произвело сет на резултати со проверка дали mysqli_stmt_result_metadata() returns
false.
Параметри
-
statement објектот како свој прв аргумент. mysqli_stmt Само процедурален стил: А mysqli_stmt_init().
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.
Errors/Exceptions
Ако е овозможено известување за грешки на 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();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %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);
/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));Горните примери ќе дадат излез:
Number of rows: 20.
Види Исто така
- mysqli_prepare() - Подготвува SQL израз за извршување
- mysqli_stmt_result_metadata() - Враќа метаподатоци од сет на резултати од подготвена изјава
- mysqli_stmt_fetch() - Презема резултати од подготвена изјава во поврзаните променливи
Белешки од корисници 4 белешки
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.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.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,