Php mysqli get result array

mysql_result

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

Возвращает содержимое одного поля из набора результата MySQL.

Работая с большими результатами запросов, следует использовать одну из функций, обрабатывающих сразу целый ряд результата (указаны ниже). Так как эти функции возвращают значение нескольких ячеек сразу, они НАМНОГО быстрее mysql_result() . Кроме того, учтите, что указание численного смещения работает намного быстрее, чем указание колонки, или колонки с таблицей через точку.

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

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Номер получаемого ряда из результата. Нумерация рядов начинается с 0 .

Имя или смещение получаемого поля.

Может быть как смещением поля, именем поля, так и именем поля вместе с таблицей (таблица.поле). Если для поля был указан псевдоним (‘select foo as bar from. ‘), используйте его вместо имени самого поля. Если не указан, возвращается первое поле.

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

Содержимое одного поля из набора результата MySQL в случае успешного выполнения, или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_result()

$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения: ‘ . mysql_error ());
>
if (! mysql_select_db ( ‘database_name’ )) die( ‘Ошибка выбора базы данных: ‘ . mysql_error ());
>
$result = mysql_query ( ‘SELECT name FROM work.employee’ );
if (! $result ) die( ‘Ошибка выполнения запроса:’ . mysql_error ());
>
echo mysql_result ( $result , 2 ); // выведет имя третьего сотрудника

Примечания

Замечание:

Вызовы функции mysql_result() не должны смешиваться с другими функциями, работающими с результатом запроса.

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

  • mysql_fetch_row() — Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
  • mysql_fetch_array() — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
  • mysql_fetch_assoc() — Возвращает ряд результата запроса в качестве ассоциативного массива
  • mysql_fetch_object() — Обрабатывает ряд результата запроса и возвращает объект

Источник

mysqli_fetch_array

Fetches one row of data from the result set and returns it as an array. Each subsequent call to this function will return the next row within the result set, or null if there are no more rows.

In addition to storing the data in the numeric indices of the result array, this function can also store the data in associative indices by using the field names of the result set as keys.

Читайте также:  Решение систем дифференциальных уравнений питон

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, the numerically indexed version of the row must be used.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP null value.

Parameters

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC , MYSQLI_NUM , or MYSQLI_BOTH .

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc() , while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

Return Values

Returns an array representing the fetched row, null if there are no more rows in the result set, or false on failure.

Examples

Example #1 mysqli_result::fetch_array() example

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 ID LIMIT 3» ;
$result = $mysqli -> query ( $query );

/* numeric array */
$row = $result -> fetch_array ( MYSQLI_NUM );
printf ( «%s (%s)\n» , $row [ 0 ], $row [ 1 ]);

/* associative array */
$row = $result -> fetch_array ( MYSQLI_ASSOC );
printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);

/* associative and numeric array */
$row = $result -> fetch_array ( MYSQLI_BOTH );
printf ( «%s (%s)\n» , $row [ 0 ], $row [ «CountryCode» ]);

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

$query = «SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3» ;
$result = mysqli_query ( $mysqli , $query );

/* numeric array */
$row = mysqli_fetch_array ( $result , MYSQLI_NUM );
printf ( «%s (%s)\n» , $row [ 0 ], $row [ 1 ]);

/* associative array */
$row = mysqli_fetch_array ( $result , MYSQLI_ASSOC );
printf ( «%s (%s)\n» , $row [ «Name» ], $row [ «CountryCode» ]);

/* associative and numeric array */
$row = mysqli_fetch_array ( $result , MYSQLI_BOTH );
printf ( «%s (%s)\n» , $row [ 0 ], $row [ «CountryCode» ]);

The above examples will output something similar to:

Kabul (AFG) Qandahar (AFG) Herat (AFG)

See Also

  • mysqli_fetch_assoc() — Fetch the next row of a result set as an associative array
  • mysqli_fetch_column() — Fetch a single column from the next row of a result set
  • mysqli_fetch_row() — Fetch the next row of a result set as an enumerated array
  • mysqli_fetch_object() — Fetch the next row of a result set as an object
  • mysqli_query() — Performs a query on the database
  • mysqli_data_seek() — Adjusts the result pointer to an arbitrary row in the result
Читайте также:  Php add objects to array

User Contributed Notes

Источник

The mysqli_result class

Represents the result set obtained from a query against the database.

Class synopsis

public fetch_object ( string $class = «stdClass» , array $constructor_args = [] ): object | null | false

Properties

Stores whether the result is buffered or unbuffered as an int ( MYSQLI_STORE_RESULT or MYSQLI_USE_RESULT , respectively).

Changelog

Version Description
8.0.0 mysqli_result implements IteratorAggregate now. Previously, Traversable was implemented instead.

Table of Contents

  • mysqli_result::__construct — Constructs a mysqli_result object
  • mysqli_result::$current_field — Get current field offset of a result pointer
  • mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
  • mysqli_result::fetch_all — Fetch all result rows as an associative array, a numeric array, or both
  • mysqli_result::fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_result::fetch_assoc — Fetch the next row of a result set as an associative array
  • mysqli_result::fetch_column — Fetch a single column from the next row of a result set
  • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  • mysqli_result::fetch_field — Returns the next field in the result set
  • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  • mysqli_result::fetch_object — Fetch the next row of a result set as an object
  • mysqli_result::fetch_row — Fetch the next row of a result set as an enumerated array
  • mysqli_result::$field_count — Gets the number of fields in the result set
  • mysqli_result::field_seek — Set result pointer to a specified field offset
  • mysqli_result::free — Frees the memory associated with a result
  • mysqli_result::getIterator — Retrieve an external iterator
  • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
  • mysqli_result::$num_rows — Gets the number of rows in the result set

User Contributed Notes 7 notes

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.

Читайте также:  Кожи питона на ощупь

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.

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)
$i++;>
return $result;>

$search=mysqli_query($connection, «select name from table_name where «);
$name=mysqli_result($search, 0, «id»);

An «mysqli_result» function where $field can be like table_name.field_name with alias or not.
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 ;
>
?>

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:

// 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 ;

Источник

Оцените статью