php中的postgresql数据库查询问题

时间:2011-05-26 04:26:38

标签: php sql postgresql

我已经编写了这段代码来显示从postgresql数据库中提取的项目列表,这是一个有点冗长的代码,所以我在这里放了一点点来解决我遇到的问题。我得到的结果在下面给出了`test1m

Resource id #4
Galle
Kandy
Anuradhapura
Dambulla
Hambantota
Colombo
Hikkaduwa
test2
Resource id #4

但预计会是这个

test1m
Resource id #4
Galle
Kandy
Anuradhapura
Dambulla
Hambantota
Colombo
Hikkaduwa
test2
Resource id #4 Galle
Kandy
Anuradhapura
Dambulla
Hambantota
Colombo
Hikkaduwa

这是代码

$date = date("Y-m-d");
$dbh = pg_connect("host=localhost dbname= drupal_test user=usrx password=123");
if (!$dbh) {
  die("Error in connection: " . pg_last_error());
}           

$sql1 = "SELECT * 
           FROM node, modify_dates, node_counter 
          WHERE node.nid = modify_dates.nid 
            AND node.nid = node_counter.nid 
            AND modify_dates.nid = node_counter.nid 
            AND node_counter.totalcount < '1000' 
            AND node.type = 'city_guide' 
       ORDER BY modify_dates.lmd";
$sel1 = pg_query($sql1);

$sql2 = "SELECT * 
           FROM node, modify_dates, node_counter 
          WHERE node.nid = modify_dates.nid 
            AND node.nid = node_counter.nid 
            AND modify_dates.nid = node_counter.nid 
            AND node_counter.totalcount > '1000' 
            AND node.type = 'city_guide' 
       ORDER BY modify_dates.lmd";
$sel2 = pg_query($sql2);

if(pg_num_rows($sel1) > 0) {
  echo "test1";
  chooseItems($sel1);                           
} else if(pg_num_rows($sel2) > 0) {
  echo "test1m<br/>";
  chooseItems($sel2);                           
} 

if(pg_num_rows($sel2) > 0) {
  echo "test2<br/>";
  chooseItems($sel2);                           
} else if(pg_num_rows($sel1) > 0) {
  echo "test2m<br/>";
  chooseItems($sel1);                           
}       

function chooseItems($sel) {
  echo $sel."<br/>";                                    
  $m = 0;

  while($row = pg_fetch_array($sel)) {
    echo $row['title']."<br/>";                 
    $m = $m+1;                  
  }             
}               

pg_close($dbh); 

1 个答案:

答案 0 :(得分:2)

问题是pg_fetch_array()消耗了一行输入。读完所有行后就是这样。但是消耗不会影响查询返回的行数。所以pg_num_rows()保持不变,但是当你尝试通过pg_fetch_array()读取更多数据时,没有什么可读的,它已被消耗。

您可以再次查询以刷新内容。