Num rows php параметры

mysqli_num_rows

Поведение функции mysqli_num_rows() зависит от того, используется ли буферизованная или не буферизованная результирующая выборка. Функция возвращает 0 для небуферизованных наборов результатов, если с сервера не были получены все строки.

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

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

Возвращает целое число ( int ), представляющее количество выбранных строк. Возвращает 0 в небуферизованном режиме, если с сервера не были получены все строки.

Замечание:

Если количество строк больше, чем PHP_INT_MAX , число будет возвращено как строка ( string ).

Примеры

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

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

$result = $mysqli -> query ( «SELECT Code, Name FROM Country ORDER BY Name» );

/* Получение количества строк в наборе результатов */
$row_cnt = $result -> num_rows ;

printf ( «Получено %d строк.\n» , $row_cnt );
?>

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

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

$result = mysqli_query ( $link , «SELECT Code, Name FROM Country ORDER BY Name» );

/* Получение количества строк в наборе результатов */
$row_cnt = mysqli_num_rows ( $result );

printf ( «Получено %d строк.\n» , $row_cnt );

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

Примечания

Замечание:

В отличие от функции mysqli_stmt_num_rows() , у этой функции нет варианта в объектно-ориентированном стиле. В объектно-ориентированном стиле используйте метод чтения.

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

  • mysqli_affected_rows() — Получает число строк, затронутых предыдущей операцией MySQL
  • mysqli_store_result() — Передаёт на клиента результирующий набор последнего запроса
  • mysqli_use_result() — Готовит результирующий набор на сервере к использованию
  • mysqli_query() — Выполняет запрос к базе данных
  • mysqli_stmt_num_rows() — Возвращает количество строк, полученных с сервера

User Contributed Notes 3 notes

If you have problems making work this num_rows, you have to declare ->store_result() first.

$mysqli = new mysqli ( «localhost» , «root» , «» , «tables» );

$query = $mysqli -> prepare ( «SELECT * FROM table1» );
$query -> execute ();
$query -> store_result ();

This function doesn’t work with LIMIT used jointly with SQL_CALC_FOUND_ROWS. If you want to obtain the total rows found you must do it manually, example:

public function errorList ( int $limit = 25 , int $offset = 0 ) $errorList = array();
$result = $this -> con -> query ( «SELECT SQL_CALC_FOUND_ROWS id, erreur FROM Erreurs ORDER BY id DESC LIMIT $limit OFFSET $offset » );
while( $row = $result -> fetch_assoc ()) $errorList [] = new Erreur ( $row );
>
$result -> free ();
// $foundRows = $result->num_rows; // 25
$foundRows = $this -> con -> query ( «SELECT FOUND_ROWS() as foundRows» );
$this -> foundRows = $foundRows -> fetch_assoc (); // 178
return $errorList ;
>
?>

in php 5.3.8 had unexpected troubles when checking for mysqli_result::$num_rows
If the result of the query is empty then var_dump of the result will be like this:
class mysqli_result#5 (5) public $current_field => NULL
public $field_count => NULL
public $lengths => NULL
public $num_rows => NULL
public $type => NULL
>
but var_dump($result->num_rows) will give integer-typed zero instead of NULL:
int(0)

Источник

mysqli_stmt_num_rows

Возвращает количество строк, помещённых в буфер в выражении. Функция будет работать только после вызова mysqli_stmt_store_result() для буферизации всего набора результатов в дескрипторе оператора.

Функция возвращает 0 , если с сервера не были получены все строки.

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

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

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

Целое число ( int ), представляющее количество буферизованных строк. Возвращает 0 в небуферизованном режиме, если с сервера не были получены все строки.

Замечание:

Если количество строк больше, чем PHP_INT_MAX , число будет возвращено как строка ( string ).

Примеры

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

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 Процедурный стиль

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

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

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

  • mysqli_stmt_store_result() — Сохраняет набор результатов во внутреннем буфере
  • mysqli_stmt_affected_rows() — Возвращает общее количество строк, изменённых, удалённых, вставленных или сопоставленных последним выполненным выражением
  • mysqli_prepare() — Подготавливает SQL выражение к выполнению

User Contributed Notes 1 note

Please be advised, for people who sometimes miss to read this important Manual entry for this function:

If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.

mysqli_stmt_store_result( ) saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.

If you do not save the result set but still want to use this function you have to actually loop through the result set one row at a time using mysqli_stmt_fetch( ) before using this function to determine the number of rows.

A thought though, if you want to determine the number of rows without storing the result set and after looping through it, why not just simply keep an internal counter in your loop every time a row is fetched and save the function call.

In short, this function is only really useful if you save the result set and want to determine the number of rows before looping through it, otherwise you can pretty much recreate its use like I suggested.

Источник

pg_num_rows

pg_num_rows() will return the number of rows in an PgSql\Result instance.

Note:

This function used to be called pg_numrows() .

Parameters

Return Values

The number of rows in the result. On error, -1 is returned.

Changelog

Examples

Example #1 pg_num_rows() example

$result = pg_query ( $conn , «SELECT 1» );

$rows = pg_num_rows ( $result );

echo $rows . » row(s) returned.\n» ;
?>

The above example will output:

See Also

  • pg_num_fields() — Returns the number of fields in a result
  • pg_affected_rows() — Returns number of affected records (tuples)

User Contributed Notes 3 notes

As mentioned, if you are performing an INSERT/UPDATE or DELETE query and want to know the # of rows affected, you should use pg_affected_rows() instead of pg_num_rows().

However, you can also exploit postgres’s RETURNING clause in your query to auto-select columns from the affected rows. This has the advantage of being able to tell not only how many rows a query affects, but exactly which rows those were, especially if you return a primary-key column.

// Example query. Let’s say that this updates five rows in the source table.
$res = pg_query ( «Update foo set bar = ‘new data’ where foo.bar = ‘old data’ » );
pg_num_rows ( $res ); // 0
pg_affected_rows ( $res ); // 5
pg_fetch_all ( $res ); // FALSE

// Same query, with a RETURNING clause.
$res = pg_query ( «Update foo set bar = ‘new data’ where foo.bar = ‘old data’ RETURNING foo.pkey» );
pg_num_rows ( $res ); // 5
pg_affected_rows ( $res ); // 5
pg_fetch_all ( $res ); // Multidimensional array corresponding to our affected rows & returned columns
?>

Not sure why this documentation doesn’t have the following note:
Note: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE query.

Found on other resources. Adding here in case someone else is looking for the info.

About preceding note, you shouldn’t use pg_num_rows() for this.
You should have instead a look at pg_affected_rows().

  • PostgreSQL Functions
    • pg_​affected_​rows
    • pg_​cancel_​query
    • pg_​client_​encoding
    • pg_​close
    • pg_​connect_​poll
    • pg_​connect
    • pg_​connection_​busy
    • pg_​connection_​reset
    • pg_​connection_​status
    • pg_​consume_​input
    • pg_​convert
    • pg_​copy_​from
    • pg_​copy_​to
    • pg_​dbname
    • pg_​delete
    • pg_​end_​copy
    • pg_​escape_​bytea
    • pg_​escape_​identifier
    • pg_​escape_​literal
    • pg_​escape_​string
    • pg_​execute
    • pg_​fetch_​all_​columns
    • pg_​fetch_​all
    • pg_​fetch_​array
    • pg_​fetch_​assoc
    • pg_​fetch_​object
    • pg_​fetch_​result
    • pg_​fetch_​row
    • pg_​field_​is_​null
    • pg_​field_​name
    • pg_​field_​num
    • pg_​field_​prtlen
    • pg_​field_​size
    • pg_​field_​table
    • pg_​field_​type_​oid
    • pg_​field_​type
    • pg_​flush
    • pg_​free_​result
    • pg_​get_​notify
    • pg_​get_​pid
    • pg_​get_​result
    • pg_​host
    • pg_​insert
    • pg_​last_​error
    • pg_​last_​notice
    • pg_​last_​oid
    • pg_​lo_​close
    • pg_​lo_​create
    • pg_​lo_​export
    • pg_​lo_​import
    • pg_​lo_​open
    • pg_​lo_​read_​all
    • pg_​lo_​read
    • pg_​lo_​seek
    • pg_​lo_​tell
    • pg_​lo_​truncate
    • pg_​lo_​unlink
    • pg_​lo_​write
    • pg_​meta_​data
    • pg_​num_​fields
    • pg_​num_​rows
    • pg_​options
    • pg_​parameter_​status
    • pg_​pconnect
    • pg_​ping
    • pg_​port
    • pg_​prepare
    • pg_​put_​line
    • pg_​query_​params
    • pg_​query
    • pg_​result_​error_​field
    • pg_​result_​error
    • pg_​result_​seek
    • pg_​result_​status
    • pg_​select
    • pg_​send_​execute
    • pg_​send_​prepare
    • pg_​send_​query_​params
    • pg_​send_​query
    • pg_​set_​client_​encoding
    • pg_​set_​error_​verbosity
    • pg_​socket
    • pg_​trace
    • pg_​transaction_​status
    • pg_​tty
    • pg_​unescape_​bytea
    • pg_​untrace
    • pg_​update
    • pg_​version

    Источник

    mysql_num_rows

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

    Описание

    Возвращает количество рядов результата запроса. Эта команда работает только с запросами SELECT или SHOW, возвращающих актуальный результат запроса. Чтобы получить количество рядов, обработанных функциями INSERT, UPDATE, REPLACE и DELETE, используйте функцию mysql_affected_rows() .

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

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

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

    Количество рядов в результате запроса в случае успеха или FALSE в случае возникновения ошибки.

    Примеры

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

    $link = mysql_connect ( «localhost» , «mysql_user» , «mysql_password» );
    mysql_select_db ( «database» , $link );

    $result = mysql_query ( «SELECT * FROM table1» , $link );
    $num_rows = mysql_num_rows ( $result );

    echo «Получено $num_rows рядов\n» ;

    Примечания

    Замечание:

    При использовании mysql_unbuffered_query() функция mysql_num_rows() не вернёт корректного значения до тех пор, пока все ряды не будут получены.

    Замечание:

    Для обратной совместимости может быть использован следующий устаревший псевдоним: mysql_numrows()

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

    • mysql_affected_rows() — Возвращает число затронутых прошлой операцией рядов
    • mysql_connect() — Открывает соединение с сервером MySQL
    • mysql_data_seek() — Перемещает внутренний указатель в результате запроса
    • mysql_select_db() — Выбирает базу данных MySQL
    • mysql_query() — Посылает запрос MySQL

    Источник

    Читайте также:  Abstract class implements interface java
Оцените статью