如何阻止pg_fetch_result/pg_fetch_array的内部结果指针前移?
pg_fetch_result 指针自动前移的原因及解决办法
为什么内部结果指针会前移?
pg_fetch_result 的设计逻辑就是如此:当你只传入结果集和字段名(或字段索引)两个参数时,它会读取当前指针指向的行的对应字段,然后自动将结果集指针下移一行。
你的示例代码里:
- 第一次调用
pg_fetch_result($result, "user_name"),读取第1行的user_name,指针移到第2行; - 第二次调用读取第2行的
user_add,指针移到第3行; - 第三次调用读取第3行的
mobile,完全符合这个函数的默认行为。
怎么阻止指针前移?
有两种可靠的解决方式:
1. 显式指定行号
pg_fetch_result 支持三个参数:pg_fetch_result($result, $row_num, $field),直接指定要读取的行号(从0开始计数),这样函数不会自动移动指针,每次都读取你指定的行:
$result = pg_query($db, "SELECT user_name, user_add, mobile FROM user_profile WHERE id=1 OR id=2 OR id=3"); $username = pg_fetch_result($result, 0, "user_name"); // 明确取第1行的用户名 $address = pg_fetch_result($result, 0, "user_add"); // 还是取第1行的地址 $mobile = pg_fetch_result($result, 0, "mobile"); // 取第1行的手机号
2. 先读取整行到数组,再从数组取值
更高效的方式是用 pg_fetch_assoc 或 pg_fetch_array 先把目标行一次性读取到内存数组中,之后直接操作数组,彻底避开指针问题:
$result = pg_query($db, "SELECT user_name, user_add, mobile FROM user_profile WHERE id=1 OR id=2 OR id=3"); $row = pg_fetch_assoc($result); // 读取第1行到关联数组 $username = $row['user_name']; $address = $row['user_add']; $mobile = $row['mobile'];
这种方法不仅避免了指针混乱,还减少了对数据库结果集的重复操作,性能更好,代码逻辑也更清晰。
内容的提问来源于stack exchange,提问作者gojiraki
相关产品推荐
相关产品推荐

