2024 年日本 PHP 研討會

mysqli_result::data_seek

mysqli_data_seek

(PHP 5, PHP 7, PHP 8)

mysqli_result::data_seek -- mysqli_data_seek將結果指標調整到結果中的任意列

說明

物件導向風格

公開 mysqli_result::data_seek(整數 $offset): 布林值

程序式風格

mysqli_data_seek(mysqli_result $result, 整數 $offset): 布林值

mysqli_data_seek() 函式會將結果集中的結果指標指向由 offset 指定的任意位置。

參數

result

僅限程序式風格:由 mysqli_query()mysqli_store_result()mysqli_use_result()mysqli_stmt_get_result() 返回的 mysqli_result 物件。

offset

列的偏移量。必須介於零和總列數減一之間 (0..mysqli_num_rows() - 1)。

返回值

成功時返回 true,失敗時返回 false

範例

範例 #1 mysqli::data_seek() 範例

物件導向風格

<?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";
$result = $mysqli->query($query);

/* 指向第 401 列 */
$result->data_seek(400);

/* 取得單列資料 */
$row = $result->fetch_row();

printf("城市: %s 國家代碼: %s\n", $row[0], $row[1]);

程序式風格

<?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";

$result = mysqli_query($link, $query);

/* 移動到第 401 列 */
mysqli_data_seek($result, 400);

/* 取得單一列資料 */
$row = mysqli_fetch_row($result);

printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);

以上範例會輸出

City: Benin City  Countrycode: NGA

範例 #2 調整迭代時的結果指標

當需要以自定義順序迭代結果集,或是在多次迭代時需要重rewind結果集,這個函式會很有用。

<?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 15,4";
$result = $mysqli->query($query);

/* 以相反的順序迭代結果集 */
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);

/* 取得單列資料 */
$row = $result->fetch_row();

printf("城市: %s 國家代碼: %s\n", $row[0], $row[1]);
}

/* 重設指標到結果集的開頭 */
$result->data_seek(0);

print
"\n";

/* 再次迭代相同的結果集 */
while ($row = $result->fetch_row()) {
printf("城市: %s 國家代碼: %s\n", $row[0], $row[1]);
}

以上範例會輸出

City: Acmbaro  Countrycode: MEX
City: Abuja  Countrycode: NGA
City: Abu Dhabi  Countrycode: ARE
City: Abottabad  Countrycode: PAK

City: Abottabad  Countrycode: PAK
City: Abu Dhabi  Countrycode: ARE
City: Abuja  Countrycode: NGA
City: Acmbaro  Countrycode: MEX

注意事項

說明:

此函式只能用於使用 mysqli_store_result()mysqli_query()mysqli_stmt_get_result() 函式取得的緩衝結果。

另請參閱

新增註記

使用者貢獻的註記

此頁面沒有使用者貢獻的註記。
To Top