PHP 8.3.4 Released!

mysqli_stmt::$affected_rows

mysqli_stmt_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows直近に実行されたステートメントで変更・削除・追加、あるいは選択された行の総数を返す

説明

オブジェクト指向型

手続き型

mysqli_stmt_affected_rows(mysqli_stmt $statement): int|string

INSERTUPDATE あるいは DELETE クエリによって変更された行の数を返します。

SELECT クエリに対しては、 mysqli_stmt_num_rows() 関数と同じように動作します。

パラメータ

stmt

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

戻り値

ゼロより大きい整数の場合、変更または取得された行の数を示します。ゼロの場合は、 UPDATE で 1 行も更新されなかった・ WHERE 句にマッチする行がなかった・ あるいはまだクエリが実行されていないのいずれかであることを示します。 -1 は、クエリがエラーを返したか、 SELECT 文については、 mysqli_stmt_store_result() をコールする前に mysqli_stmt_affected_rows() がコールされたことを示します。

注意:

変更された行の数が PHP の int 型の最大値をこえる場合は、変更された 行の数は文字列として返されます。

例1 mysqli_stmt_affected_rows() の例

オブジェクト指向型

<?php

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

/* 一時テーブルを作成します */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* 文を準備します */
$stmt = $mysqli->prepare($query);

/* プレースホルダに変数をバインドします */
$code = 'A%';
$stmt->bind_param("s", $code);

/* 文を実行します */
$stmt->execute();

printf("Rows inserted: %d\n", $stmt->affected_rows);

手続き型

<?php

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

/* 一時テーブルを作成します */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* 文を準備します */
$stmt = mysqli_prepare($link, $query);

/* プレースホルダに変数をバインドします */
$code = 'A%';
mysqli_stmt_bind_param($stmt, "s", $code);

/* 文を実行します */
mysqli_stmt_execute($stmt);

printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

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

Rows inserted: 17

参考

add a note

User Contributed Notes 2 notes

up
28
Carl Olsen
18 years ago
It appears that an UPDATE prepared statement which contains the same data as that already in the database returns 0 for affected_rows. I was expecting it to return 1, but it must be comparing the input values with the existing values and determining that no UPDATE has occurred.
up
-10
Chuck
16 years ago
I'm not sure whether or not this is the intended behavior, but I noticed through testing that if you were to use transactions and prepared statements together and you added a single record to a database using a prepared statement, but later rolled it back, mysqli_stmt_affected_rows will still return 1.
To Top