phppostgresql

To select a specific column from a table using php postgres


I have table of 5000+ rows and 8+ columns like,

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  -   -   -   -

I am developing a web application, in that user will select a column like rainfall/temp/humidity and for a particular date.

Can anyone guide me how to query for this in php-postgres. (database:postgres, table:weatherdata, user:user, password:password)

Thanks in advance.


Solution

  • You can use some code like this:

    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);
    }
    

    Now you can invoke it:

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