- mysqli_stmt_num_rows
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 1 note
- PHP mysqli_stmt_num_rows() Function
- Syntax
- Parameters
- Return Values
- PHP Version
- Example
- Example
- Example
- mysqli_stmt_num_rows
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- mysqli_stmt_num_rows
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 1 note
mysqli_stmt_num_rows
Возвращает число строк в результате запроса. Результат выполнения mysqli_stmt_num_rows() зависит от того использовалась ли mysqli_stmt_store_result() для буферизации результата выборки в дескрипторе.
Если используется mysqli_stmt_store_result(), mysqli_stmt_num_rows() может быть вызвана в тот же момент.
Список параметров
stmt — Только для процедурного стиля: Идентификатор выражения, полученный с помощью mysqli_stmt_init().
Возвращаемые значения
Целое число, отражающее число строк в результате запроса.
Примеры
Пример #1 Объектно-ориентированный стиль
/* Открыть соединение */ $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* Проверить соединение */ if (mysqli_connect_errno()) < printf("Ошибка соединения: %s\n", mysqli_connect_error()); exit(); >$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; if ($stmt = $mysqli->prepare($query)) < /* Выполнить запрос */ $stmt->execute(); /* Сохранить результат */ $stmt->store_result(); printf("Число строк: %d.\n", $stmt->num_rows); /* Закрыть выражение */ $stmt->close(); > /* Закрыть соединение */ $mysqli->close();
Пример #2 Процедурный стиль
/* Открыть соединение */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* Проверить соединение */ if (mysqli_connect_errno()) < printf("Ошибка соединения: %s\n", mysqli_connect_error()); exit(); >$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; if ($stmt = mysqli_prepare($link, $query)) < /* Выполнить запрос */ mysqli_stmt_execute($stmt); /* Сохранить результат */ mysqli_stmt_store_result($stmt); printf("Число строк: %d.\n", mysqli_stmt_num_rows($stmt)); /* Закрыть выражение */ mysqli_stmt_close($stmt); >/* Закрыть соединение */ mysqli_close($link);
Результат выполнения данных примеров:
Смотрите также
- mysqli_stmt_affected_rows() — Возвращает общее количество строк, измененных, удаленных или добавленных последним выполненным выражением
- mysqli_prepare() — Подготавливает SQL выражение к выполнению
- mysqli_stmt_store_result() — Передает результирующий набор запроса на клиента
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.
Описание класса mysqli_stmt, примеры использования класса mysqli_stmt.
PHP mysqli_stmt_num_rows() Function
The mysqli_stmt_num_rows() function accepts a statement object as a parameter and returns the number of rows in the result set of the given statement.
Syntax
Parameters
This is an object representing a statement executing an SQL query.
Return Values
PHP mysqli_stmt_num_rows() function returns an integer value indicating the number of rows in the resultset returned by the statement.
PHP Version
This function was first introduced in PHP Version 5 and works works in all the later versions.
Example
Following example demonstrates the usage of the mysqli_stmt_num_rows() function (in procedural style) −
This will produce following result −
Table Created. Records Inserted. Number of rows in the table: 3
Example
In object oriented style the syntax of this function is $con->num_rows; Following is the example of this function in object oriented style $minus;
query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); print("Table Created. \n"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Records Inserted. \n"); $stmt = $con -> prepare( "SELECT * FROM Test"); //Executing the statement $stmt->execute(); $stmt->store_result(); //Number of rows $count = $stmt ->num_rows; print("Rows affected ".$count); //Closing the statement $stmt->close(); //Closing the connection $con->close(); ?>
This will produce following result −
Table Created. Records Inserted. Number of rows in the table: 3
Example
Assume we have created a table named cricketers with the following data $minus;
mysql> select * from cricketers; +----+------------+------------+---------------+----------------+ | ID | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | +----+------------+------------+---------------+----------------+ | 1 | Shikhar | Dhawan | 1981-12-05 | Delhi | | 2 | Jonathan | Trott | 1981-04-22 | CapeTown | | 3 | Kumara | Sangakkara | 1977-10-27 | Matale | | 4 | Virat | Kohli | 1988-11-05 | Delhi | | 5 | Rohit | Sharma | 1987-04-30 | Nagpur | | 6 | Ravindra | Jadeja | 1988-12-06 | Nagpur | +----+------------+------------+---------------+----------------+ 6 rows in set (0.07 sec)
If you try to invoke this function directly, since the results haven’t stored yet, it returns 0 −
This will produce following result −
Number of rows in the table: 0
mysqli_stmt_num_rows
Возвращает число строк в результате запроса. Результат выполнения mysqli_stmt_num_rows() зависит от того использовалась ли mysqli_stmt_store_result() для буферизации результата выборки в дескрипторе.
Если используется mysqli_stmt_store_result() , mysqli_stmt_num_rows() может быть вызвана в тот же момент.
Список параметров
Только для процедурного стиля: Идентификатор выражения, полученный с помощью mysqli_stmt_init() .
Возвращаемые значения
Целое число, отражающее число строк в результате запроса.
Примеры
Пример #1 Объектно-ориентированный стиль
/* Открыть соединение */
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );
?php
/* Проверить соединение */
if ( mysqli_connect_errno ()) printf ( «Ошибка соединения: %s\n» , mysqli_connect_error ());
exit();
>
$query = «SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20» ;
if ( $stmt = $mysqli -> prepare ( $query ))
/* Выполнить запрос */
$stmt -> execute ();
/* Сохранить результат */
$stmt -> store_result ();
printf ( «Число строк: %d.\n» , $stmt -> num_rows );
/* Закрыть выражение */
$stmt -> close ();
>
/* Закрыть соединение */
$mysqli -> close ();
?>
Пример #2 Процедурный стиль
/* Открыть соединение */
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );
?php
/* Проверить соединение */
if ( mysqli_connect_errno ()) printf ( «Ошибка соединения: %s\n» , mysqli_connect_error ());
exit();
>
$query = «SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20» ;
if ( $stmt = mysqli_prepare ( $link , $query ))
/* Выполнить запрос */
mysqli_stmt_execute ( $stmt );
/* Сохранить результат */
mysqli_stmt_store_result ( $stmt );
printf ( «Число строк: %d.\n» , mysqli_stmt_num_rows ( $stmt ));
/* Закрыть выражение */
mysqli_stmt_close ( $stmt );
>
/* Закрыть соединение */
mysqli_close ( $link );
?>
Результат выполнения данных примеров:
Смотрите также
- mysqli_stmt_affected_rows() — Возвращает общее количество строк, измененных, удаленных или добавленных последним выполненным выражением
- mysqli_prepare() — Подготавливает SQL выражение к выполнению
- mysqli_stmt_store_result() — Передает результирующий набор запроса на клиента
mysqli_stmt_num_rows
Returns the number of rows buffered in the statement. This function will only work after mysqli_stmt_store_result() is called to buffer the entire result set in the statement handle.
This function returns 0 unless all rows have been fetched from the server.
Parameters
Procedural style only: A mysqli_stmt object returned by mysqli_stmt_init() .
Return Values
An int representing the number of buffered rows. Returns 0 in unbuffered mode unless all rows have been fetched from the server.
Note:
If the number of rows is greater than PHP_INT_MAX , the number will be returned as a string .
Examples
Example #1 Object-oriented style
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 );
Example #2 Procedural style
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 ));
The above examples will output:
See Also
- mysqli_stmt_store_result() — Stores a result set in an internal buffer
- mysqli_stmt_affected_rows() — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
- mysqli_prepare() — Prepares an SQL statement for execution
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.