使用php postgres从表中选择特定列

时间:2012-03-21 12:27:55

标签: php postgresql

我有5000多行和8+列的表,如

Station Lat Long    Date    Rainfall    Temp    Humidity    Windspeed
Abcd    -   -   09/09/1996  -   -   -   -
Abcd    -   -   10/09/1996  -   -   -   -
Abcd    -   -   11/09/1996  -   -   -   -
Abcd    -   -   12/09/1996  -   -   -   -
Efgh    -   -   09/09/1996  -   -   -   -
Efgh    -   -   10/09/1996  -   -   -   -
Efgh    -   -   11/09/1996  -   -   -   -
Efgh    -   -   12/09/1996  -   -   -   -

我正在开发一个Web应用程序,用户将选择一个像降雨/温度/湿度和特定日期的列。

任何人都可以指导我如何在php-postgres中查询。 (数据库:postgres,表:weatherdata,用户:用户,密码:密码)

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

public function getData ($date, $columnsToShow = null) {

  /* You could check the parameters here:
   *   $date is string and not empty
   *    $columnsToShow is an array or null.
   */ 

  if (isset ($columnsToShow))
    $columnsToShow = implode (',', $columnsToShow);
  else  $columnsToShow = "*";

  $query = "select {$columnsToShow}
            from table
            where date = '{$date}'";

  $result = array();
  $conex = pg_connect ("host=yourHost user=yourUser password=yourUser dbname=yourDatabase");
  if (is_resource ($conex)) {
    $rows = pg_query ($conex, $query);

    if ($rows) {
      while ($data = pg_fetch_array ($rows, null, 'PGSQL_ASSOC'))
         $result[] = $data;
    }
  }
  return (empty ($result) ? null : $result);
}

现在您可以调用,例如,这样:

getData ('2012-03-21', array ('Station', 'Rainfall'));

我希望你能服务。