传递参数查询

时间:2017-04-11 01:44:14

标签: php mysql

根据城市的说法,我试图获得拉特。当我最后在查询中写出城市('Buffalo')时,它可以工作。我想使用不同的城市。

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传递给查询?

1 个答案:

答案 0 :(得分: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 . "'");