[mapserver-users] Query by attributes with PHP/MapScript

Puneet Kishor pkishor at GeoAnalytics.com
Wed Oct 2 10:28:54 EDT 2002


On Wednesday, October 2, 2002, at 04:41  AM, Armin Burger wrote:

> Hi all,
>
> I would like to query shapefiles based on their attibutes using
> PHP/MapScript, like
>
>   street='mainstreet' and city='newtown'
>
> and then get back all records, including for instance the bounding box
> of the shape.
>
> There is the function QueryByAttributes, but as I saw in the mail
> archives you have to set a filteritem and then a filter on the layer.
> That can only use one field as filteritem. I would need 2 or even more
> fields used in the query.
>
> I was thinking about using basic PHP functions for dBase.
> Unfortunately the dBase support of pure PHP seems to be very 
> rudimentary
> and does not allow queries. There is the Pear DB module, but there is 
> no
> documentation to what extent dBase files are supported.

hmmmm... does too. And it is not rudimentary at all... in fact, it is 
only limited by the limits of the dbase format (which is a pretty poor 
limit).

Here is a dbase function that will query whatever you want --

//{{{ getDbfRowid($dbf, $field, $arVals).
// Get dbf row_ids from a $dbf given an array of $arVals for a field 
$field
//
function getDbfRowid($dbf, $field, $arVals) {
   $db = dbase_open($dbf, 0);                        // open the dbase 
file
   $nr = dbase_numrecords($db);                      // get number of 
records

   $arResult = array();                              // new array to 
hold row_ids

   for($i=1; $i <= $nr; $i++) {                     // loop from 1 to $nr
     $temp = dbase_get_record($db, $i);              // assign fields to 
$ar_temp
     foreach($arVals as $val) {                     // loop thru all the 
$gis_keys
       if(chop($temp[2]) == "$val") {
         // create a hash of val and row_id
         $hsResult = array("val" => $val, "row_id" => $i);
         array_push($arResult, $hsResult);           // now push the 
hash into the array
       }
     }
   }

   dbase_close($db);
   return $arResult;    // return the array of hashes
} //}}}

This allows you to, for example, find the rows where field is "street" 
and the matches you are looking for are "mainstreet", "divisionstreet", 
"highstreet", etc. Use those row_ids as indexes for the shapefile to 
zoom to the relevant features.

pk/




More information about the mapserver-users mailing list