The mysqli_result class
(PHP 5, PHP 7)
Введение
Представляет результирующий набор, полученный из запроса в базу данных.
Список изменений
Версия | Описание |
---|---|
5.4.0 | Добавлена поддержка Iterator, так как mysqli_result теперь реализует Traversable. |
Обзор классов
mysqli_result
implements
Traversable
{
/* Свойства */
int $current_field
;
int $field_count;
array $lengths;
int $num_rows;
/* Методы */
}Содержание
- mysqli_result::$current_field — Получает смещение указателя по отношению к текущему полю
- mysqli_result::data_seek — Перемещает указатель результата на выбранную строку
- mysqli_result::fetch_all — Выбирает все строки из результирующего набора и помещает их в ассоциативный массив, обычный массив или в оба
- mysqli_result::fetch_array — Выбирает одну строку из результирующего набора и помещает ее в ассоциативный массив, обычный массив или в оба
- mysqli_result::fetch_assoc — Извлекает результирующий ряд в виде ассоциативного массива
- mysqli_result::fetch_field_direct — Получение метаданных конкретного поля
- mysqli_result::fetch_field — Возвращает следующее поле результирующего набора
- mysqli_result::fetch_fields — Возвращает массив объектов, представляющих поля результирующего набора
- mysqli_result::fetch_object — Возвращает текущую строку результирующего набора в виде объекта
- mysqli_result::fetch_row — Получение строки результирующей таблицы в виде массива
- mysqli_result::$field_count — Получение количества полей в результирующем наборе
- mysqli_result::field_seek — Установить указатель поля на определенное смещение
- mysqli_result::free — Освобождает память занятую результатами запроса
- mysqli_result::$lengths — Возвращает длины полей текущей строки результирующего набора
- mysqli_result::$num_rows — Получает число рядов в результирующей выборке
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MySQL Drivers and Plugins
- Введение
- Краткий обзор
- Краткое руководство
- Установка и настройка
- Расширение mysqli и постоянные соединения
- Предопределенные константы
- Notes
- Основная информация о функциях расширения MySQLi
- Examples
- Класс mysqli
- The mysqli_stmt class
- The mysqli_result class
- Класс mysqli_driver
- Класс mysqli_warning
- The mysqli_sql_exception class
- Синонимы и устаревшие Функции Mysqli
- Список изменений
Коментарии
Extending the MySQLi_Result
<?php
class Database_MySQLi extends MySQLi
{
public function query($query)
{
$this->real_query($query);
return new Database_MySQLi_Result($this);
}
}
class Database_MySQLi_Result extends MySQLi_Result
{
public function fetch()
{
return $this->fetch_assoc();
}
public function fetchAll()
{
$rows = array();
while($row = $this->fetch())
{
$rows[] = $row;
}
return $rows;
}
}
?>
Generally, it appears Mysqli OO vs Procedural style has no significant difference in speed, at least with the more generally used functions and methods (connect, close, query, free, etc).
With the fetch_* family of functions and methods dealing with result rows, however, Procedural wins out. Averaging over a hundred or so tests with a result set of 180,000 records, and using mysqli_fetch_*() functions vs. their mysqli_result::fetch_*() counterpart object methods to read and iterate over all records, all of the mysqli_fetch_*() functions win by ~0.1 seconds less.
This is interesting considering we're dealing with the same result object in both styles.
This was using Vistax64, PHP5.3.2, Mysql 5.1.45, using a bit of this code:
<?php
// procedural - takes 0.1 seconds less than OO here
$stopwatch = microtime(true);
while($row = mysqli_fetch_assoc($result)){
++$z;
}
echo microtime(true) - $stopwatch;
// OO
$stopwatch = microtime(true);
while($row = $result->fetch_assoc()){
++$z;
}
echo microtime(true) - $stopwatch;
?>
storing this object in ANY kind will result in storing an empty object... if you try to serialize it dump it or do anything with it you will end up with a empty object.
you have to pull all data out f the object and then store the data... no other way.
Converting an old project from using the mysql extension to the mysqli extension, I found the most annoying change to be the lack of a corresponding mysql_result function in mysqli. While mysql_result is a generally terrible function, it was useful for fetching a single result field *value* from a result set (for example, if looking up a user's ID).
The behavior of mysql_result is approximated here, though you may want to name it something other than mysqli_result so as to avoid thinking it's an actual, built-in function.
<?php
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
?>
Implementing it via the OO interface is left as an exercise to the reader.
An "mysqli_result" function where $field can be like table_name.field_name with alias or not.
<?php
function mysqli_result($result,$row,$field=0) {
if ($result===false) return false;
if ($row>=mysqli_num_rows($result)) return false;
if (is_string($field) && !(strpos($field,".")===false)) {
$t_field=explode(".",$field);
$field=-1;
$t_fields=mysqli_fetch_fields($result);
for ($id=0;$id<mysqli_num_fields($result);$id++) {
if ($t_fields[$id]->table==$t_field[0] && $t_fields[$id]->name==$t_field[1]) {
$field=$id;
break;
}
}
if ($field==-1) return false;
}
mysqli_data_seek($result,$row);
$line=mysqli_fetch_array($result);
return isset($line[$field])?$line[$field]:false;
}
?>
If you're using the iterator interface on a result instance ($r), like this:
foreach ($r as $d) {
the iterated value ($d) is an associative-only array, i.e. it's the same as doing this:
while ($d = $r->fetch_assoc()) {
and NOT like this:
while ($d = $r->fetch_row()) {
so you can't access row elements by numeric index ($d[0] etc) if you use the foreach syntax.
Switching from Php5 to Php7, especially if you have worked on an ongoing, long term project, it is unfortunate that there is no mysqli_result function.
So, this may be helpfull and you can call this function as you wish. I assume you do restricted search (searching for single row or few rows only).
function mysqli_result($search, $row, $field){
$i=0; while($results=mysqli_fetch_array($search)){
if ($i==$row){$result=$results[$field];}
$i++;}
return $result;}
Simply;
$search=mysqli_query($connection, "select name from table_name where id='7'");
$name=mysqli_result($search, 0, "id");
Best wishes,