PHP mysqli_result::data_seek() / mysqli_data_seek() 函数用于将结果指针调整为任意值结果集中偏移量指定的行。
语法
//面向对象风格
public mysqli_result::data_seek(offset)
//面向过程风格
mysqli_data_seek(result, offset)
参数
结果 | 必填。 仅适用于面向过程风格:指定 mysqli_query()、mysqli_store_result()、mysqli_use_result() 或 mysqli_stmt_get_result() 返回的 mysqli_result 对象。 |
offset | 必填。 指定字段偏移量。它必须介于零和(总行数 - 1)之间。 |
返回值
成功时返回 true,成功时返回 false
示例:面向对象风格
下面的示例展示了mysqli_result::data_seek()方法的用法。
<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: ". $mysqli->connect_error;
exit();
}
//从数据库获取查询结果
$sql = "SELECT Name, Age FROM Employee ORDER BY Age";
$result = $mysqli->query($sql);
//寻找行号51
$result->data_seek(50);
//获取单行
$row = $result->fetch_row();
printf("Name: %s, Age: %d\n", $row[0], $row[1]);
//关闭连接
$mysqli->close();
?>
上述代码的输出将类似于:
Name: John, Age: 28
示例:面向过程风格
下面的示例显示mysqli_data_seek()的用法 函数。
<?php
//建立与数据库的连接
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ". mysqli_connect_error();
exit();
}
//从数据库获取查询结果
$sql = "SELECT Name, Age FROM Employee ORDER BY Age";
$result = mysqli_query($mysqli, $sql);
//寻找行号51
mysqli_data_seek($result, 50);
//获取单行
$row = mysqli_fetch_row($result);
printf("Name: %s, Age: %d\n", $row[0], $row[1]);
//关闭连接
mysqli_close($mysqli);
?>
上述代码的输出将类似于:
Name: John, Age: 28
示例:迭代时调整结果指针
当迭代结果集以强加自定义顺序或在迭代多次时倒回结果集时,此函数非常有用。考虑下面的示例:
<?php
//建立与数据库的连接
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: ". $mysqli->connect_error;
exit();
}
//从数据库获取查询结果
$sql = "SELECT Name, Age FROM Employee ORDER BY Age";
$result = $mysqli->query($sql);
//逆序迭代结果集
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
//获取单行
$row = $result->fetch_row();
printf("Name: %s, Age: %d\n", $row[0], $row[1]);
}
//重置指针
//结果集的开头
$result->data_seek(0);
echo "\n";
//再次迭代相同的结果集
while ($row = $result->fetch_row()) {
printf("Name: %s, Age: %d\n", $row[0], $row[1]);
}
//关闭连接
$mysqli->close();
?>
上述代码的输出将类似于:
Name: Adam, Age: 28
Name: John, Age: 27
Name: Kim, Age: 26
Name: Marry, Age: 23
Name: Marry, Age: 23
Name: Kim, Age: 26
Name: John, Age: 27
Name: Adam, Age: 28