PHP文件中PostgreSQL / PostGIS查询中的变量

时间:2014-04-10 20:12:59

标签: php postgresql postgis

我正在尝试在PHP文件中使用PostgreSQL / PostGIS查询中的变量。

变量需要将lat和lng值放在POINT几何体中,但是在我的代码中有些东西不能正常工作并且收到错误消息:

  

警告:pg_query():查询失败:错误:解析错误 - 无效   geometry提示:“POINT(”< - 几何中位置6处的解析错误

当我运行具有POINT值(而不是变量)的查询时

SELECT ST_AsText (the_geom) as location, name, intptlat, intptlon FROM tiger_match WHERE ST_INTERSECTS (the_geom, ST_Buffer((ST_GeomFromText('POINT(-85.1043 34.315)',4326)), 0.1));

一切正常。

我阅读了一些文章并在网上发帖但我找不到解决方案:

我在php文件中使用的整个代码如下:

<?php
$host = "localhost"; 
$user = "postgres"; 
$pass = "2907"; 
$db = "postgis";

$intptlon = pg_escape_string($_GET['intptlon']);
$intptlat = pg_escape_string($_GET['intptlat']);

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&#39;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr; 
} 

// Opens a connection to a PostgreSQL
$con = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n"); 

$query = "select ST_AsText (the_geom) as location, name, intptlat, intptlon FROM tiger_match WHERE ST_INTERSECTS (the_geom, ST_Buffer((ST_GeomFromText('POINT('$intptlon' '$intptlat')',4326)), 0.1))";
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");

header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @pg_fetch_assoc($rs)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'intptlat="' . $row['intptlat'] . '" ';
  echo 'intptlon="' . $row['intptlon'] . '" ';
  echo 'the_geom="' . $row['location'] . '" ';
  echo '/>';
}
echo '</markers>';
?>

1 个答案:

答案 0 :(得分:2)

Don't mix parameters for WKT with SQL。使用常规字符串实用程序创建WKT( T text ),然后将该字符串参数提供给查询,或使用带有数字参数的替代几何构造函数,例如ST_MakePoint(x, y)

查询应如下所示:

SELECT ST_AsText(the_geom) as location, name, intptlat, intptlon
FROM tiger_match
WHERE ST_DWithin(the_geom, ST_SetSRID(ST_MakePoint($intptlon, $intptlat), 4326), 0.1);

通常,不要使用缓冲几何来进行近距离搜索。在这种情况下,这是一点,但有些人也对整个表格这样做,这是不必要的昂贵。此外,您的距离是0.1度,这是一个无感距离单位。如果您使用geography类型,那么它将使用公制距离。