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::$num_rows
mysqli_stmt_num_rows
(PHP 5)
mysqli_stmt::$num_rows -- mysqli_stmt_num_rows — ステートメントの結果セットの行数を返す
説明
オブジェクト指向型
手続き型
結果セットの行の数を返します。mysqli_stmt_num_rows() が使用できるかどうかは、mysqli_stmt_store_result() を用いて結果をステートメントハンドルにバッファリングしているかどうかに 依存します。
mysqli_stmt_store_result() を使用した場合は、 すぐに mysqli_stmt_num_rows() をコールできます。
返り値
結果セットの行数を表す整数値を返します。
例
例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();
?>
例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.
参考
- mysqli_stmt_affected_rows() - 直近に実行されたステートメントで変更・削除・あるいは追加された行の総数を返す
- mysqli_prepare() - 実行するための SQL ステートメントを準備する
- mysqli_stmt_store_result() - プリペアドステートメントから結果を転送する
Typer85 at gmail dot com
27-Dec-2006 09:12
