运行两个连续的while循环时光标位置问题

时间:2015-03-07 22:28:20

标签: php postgresql

如果要两次运行相同的结果集,如何“重置”pg_fetch_row光标位置以从第一行开始?

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

while ($row = pg_fetch_row($result)) {     // <---- THIS WILL ALWAYS SHOW NOTHING AS IT DOESN'T START FROM the first row (0)
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

1 个答案:

答案 0 :(得分:0)

使用pg_result_seek() http://php.net/manual/en/function.pg-result-seek.php

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
  echo "An error occurred.\n";
  exit;
}

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}

pg_result_seek($result, 0);

while ($row = pg_fetch_row($result)) {
  echo "Author: $row[0]  E-mail: $row[1]";
  echo "<br />\n";
}