2017-04-11 115 views
0

我試圖根據城市獲取經緯度。當我在後面的查詢中寫入城市('布法羅')時,它就起作用了。我想使用不同的城市。通過參數查詢

public function getLatLng($data, $city) { 
    $count_data = count($data); 
    for($i = 0; $i < $count_data; $i++) { 
     $latlngs = array(); 
     $stmt = $this -> conn -> prepare("SELECT g.lat, g.lng 
      FROM news_locations AS nl INNER JOIN geolocations AS g 
      ON g.geolocation_id = nl.geolocation_id 
      WHERE nl.news_id = ". $data[$i]["news_id"] ." 
      AND nl.is_deleted = 0 AND g.city = 'Buffalo'"); 
     if ($stmt -> execute()) { 
      $stmt -> bind_result($lat, $lng); 
      while($stmt -> fetch()) { 
       $row = array(); 
       $row["lat"] = $lat; 
       $row["lng"] = $lng; 
       array_push($latlngs, $row); 
      } 
      $stmt -> close(); 
     } 
     $data[$i]['latlng'] = array_values($latlngs); 
    } 
    return $data; 
} 

我試圖寫

AND g.city = " . $city); 

也試過

AND g.city = :city"); 
if ($stmt -> execute(array('city' => $city))) { 

兩人都沒有工作。如何傳遞參數$ city來查詢?

+0

你必須變量綁定到SQL語句。 –

回答

0

連接字符串和變量:

g.city = '" . $city . "'" 

,如:

$stmt = $this -> conn -> prepare("SELECT g.lat, g.lng 
      FROM news_locations AS nl INNER JOIN geolocations AS g 
      ON g.geolocation_id = nl.geolocation_id 
      WHERE nl.news_id = ". $data[$i]["news_id"] ." 
      AND nl.is_deleted = 0 AND g.city = '" . $city . "'");