©
Ce document utilise Manuel du site Web PHP chinois Libérer
(PHP 5)
mysqli_stmt::$num_rows -- mysqli_stmt_num_rows — Return the number of rows in statements result set
面向对象风格
过程化风格
$stmt
)Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
If you use mysqli_stmt_store_result() , mysqli_stmt_num_rows() may be called immediately.
stmt
仅以过程化样式:由 mysqli_stmt_init() 返回的 statement 标识。
An integer representing the number of rows in result set.
Example #1 面向对象风格
<?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "world" );
if ( mysqli_connect_errno ()) {
printf ( "Connect failed: %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 ( "Number of rows: %d.\n" , $stmt -> num_rows );
$stmt -> close ();
}
$mysqli -> close ();
?>
Example #2 过程化风格
<?php
$link = mysqli_connect ( "localhost" , "my_user" , "my_password" , "world" );
if ( mysqli_connect_errno ()) {
printf ( "Connect failed: %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 ( "Number of rows: %d.\n" , mysqli_stmt_num_rows ( $stmt ));
mysqli_stmt_close ( $stmt );
}
mysqli_close ( $link );
?>
以上例程会输出:
Number of rows: 20.
[#1] Typer85 at gmail dot com [2006-12-27 16:12:34]
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.