2015-02-09 88 views
0

我試圖從PHP使用Postgress表中獲取數據。我向查詢提供參數,儘管我知道表中應該有數據返回,但返回的數組是空的。PHP和Postgres查詢問題

<?php 
ini_set('memory_limit', '1024M'); 
     // Connecting, selecting database 
$dbconn = pg_connect(***My connection details***) 
      or die('Could not connect: ' . pg_last_error()); 


$lat1 = 50.5; 
$lat2 = 58.0; 
$lng1 = -3.5; 
$lng2 = -7.0; 

$colour_points = 'SELECT lat,lng,price,address_string FROM house_price_data_db.main where lat>=$1 and lat<=$2 and lng>=$3 and lng<=$4'; 
$result_pinpoints_points = pg_query_params($dbconn,$colour_points,array($lat1,$lat2,$lng1,$lng2)) or die('Query failed: ' . pg_last_error()); 
$pin_points_array = array(); 

while($r = pg_fetch_assoc($result_pinpoints_points)) { 
    $pin_points_array[] = $r; 
} 

header("Content-type: application/json"); // set the header to json 
echo(json_encode(array_values($pin_points_array), JSON_NUMERIC_CHECK)); // this will return json 
pg_close($dbconn); 
?> 

有關如何解決/解決這個問題的任何建議?

+0

您是否嘗試過測試與查詢參數直接在數據庫上? – 2015-02-09 13:15:23

+0

你可以爲'$ 1','$ 2','$ 3','$ 4'指定一些值嗎? – 2015-02-09 13:26:05

+0

根據定義的'$ result_pintpoints_points'行,值被指定爲$ lat1,$ lat2,$ lng1,$ lng2。我找出了我出錯的地方,並在下面解釋。 – JellyTots 2015-02-09 13:28:16

回答

0

做了一個簡單的錯字。

'SELECT lat,lng,price,address_string FROM house_price_data_db.main where lat>=$1 and lat<=$2 and lng**>=**$3 and lng**<=**$4'; 

本來應該:

'SELECT lat,lng,price,address_string FROM house_price_data_db.main where lat>=$1 and lat<=$2 and lng**<=**$3 and lng**>=**$4'; 

的平等/低於/大於對所需的最後2個輸入符號要被改變否則就沒有輸出。這是說如果> -4和< -7這在邏輯上沒有意義。

0

Postgresql附帶一套便利的geometric typesfunctions。您可以使用point類型,而不是在兩個字段中存儲經度和緯度,甚至更好 - 創建一個latlong domain over point

利用這一點,您的查詢就會變成這樣的:

select position, price,address_string FROM house_price_data_db.main where position <@ box($1, $2, $3, $4); 

您可以直接連彙總結果在SQL,甚至他們轉成JSON:

with 
    result as (
    select 
     array_agg(main) 
    from 
     house_price_data_db.main 
    where position <@ box($1, $2, $3, $4) 
) 
select row_to_json(result) from result;