PHP 8.3.4 Released!

mysqli_stmt::$num_rows

mysqli_stmt::num_rows

mysqli_stmt_num_rows

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$num_rows -- mysqli_stmt::num_rows -- mysqli_stmt_num_rowsサーバーから取得した結果セットの行数を返す

説明

オブジェクト指向型

public mysqli_stmt::num_rows(): int|string

手続き型

mysqli_stmt_num_rows(mysqli_stmt $statement): int|string

ステートメントハンドルにバッファリングされた 結果セットの行数を返します。この関数は、 mysqli_stmt_store_result() を用いて結果全体をステートメントハンドルにバッファリングした後に使えます。

全ての行をサーバーから取得していない場合、 この関数は 0 を返します。

パラメータ

stmt

手続き型のみ: mysqli_stmt_init() が返す mysqli_stmt オブジェクト。

戻り値

バッファリングされた行数を整数値で返します。 アンバッファリングモードでは、 全ての行をサーバーから取得していない場合、 0 を返します。

注意:

行数が PHP_INT_MAX より大きい場合、 行数の数値は文字列で返されます。

例1 オブジェクト指向型

<?php

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("Number of rows: %d.\n", $stmt->num_rows);

例2 手続き型

<?php

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("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

上の例の出力は以下となります。

Number of rows: 20.

参考

add a note

User Contributed Notes 1 note

up
89
Typer85 at gmail dot com
17 years ago
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.
To Top