如何将多个GET参数合并为准备好的语句

时间:2019-07-04 13:23:25

标签: php mysql rest

我正在使用地理定位应用程序,并希望根据用户的标签返回半径结果

$tags = preg_replace('/\s+/', '', $tags);
$tags_list = [];
$tags_list = explode(',', $tags);
$tags = implode(" OR c.title=", $tags_list);
echo $tags;
if(
!empty($latitude) &&
!empty($longtitude) &&
!empty($radius)
){

    $qry = "SELECT o.id, o.title, o.icon, o.description,
    (
        6371 * acos
        (
            cos(
                radians( :lat )
            )
            * cos(
                radians( lat)
            ) * cos(
                radians( lng) - radians( :lng )
            ) + sin(
                radians( :lat )
            ) * sin(
                radians( lat)
            )
            )
            ) AS distance
            FROM objects o, category_object co, category c
            WHERE o.id = co.id_object AND co.id_category = c.id AND c.title=:title
            HAVING distance/1000 <= :radius
            ORDER BY distance/1000 ASC;";

    $stmt = $db->prepare($qry);

    $stmt->bindParam(":lat", $latitude);
    $stmt->bindParam(":lng", $longtitude);
    //Here
    $stmt->bindParam(":title", $tags);
    $stmt->bindParam(":radius", $radius);

    if($stmt->execute()){
        while ($result = $stmt->fetch(PDO::FETCH_OBJ)) {
            echo json_encode(array("type" => "FeatureCollection",
                "features" => array(
                    "type" => "Feature",
                    "geometry" => array("type" => "Point",
                        "coordinates" => [$latitude, $longtitude]),
                    "properties" => array(
                        "ID" => $result->id,
                        "icon" => $result->icon,
                        "tags" => "",
                        "title" => $result->title,
                        "description" => $result->description))), JSON_UNESCAPED_SLASHES);
            echo "\n\n";
        }

    }

如果我输入“墨西哥”,则效果很好。

localhost/../radius.php&lat=..&lng=..&radius=..&tags=mexican  <<<-- works

问题是我输入

localhost/../radius.php&lat=..&lng=..&radius=..&tags=mexican,restaurants  <<<-- doesn't work

我认为问题是我将代码转换为前置语句,这就是为什么我想知道如何更改输入方式的原因。

谢谢您的时间!

数据库连接代码

<?php
class Database {

public function getConnection() {

  $this->conn = null;

  try {
    $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
    $this->conn->exec("set names utf8");
  } catch (PDOException $e) {
    echo "connection error" . $e->getMessage();
  }

  return $this->conn;
  }

  }
  ?>

1 个答案:

答案 0 :(得分:2)

问题在这里:

$tags = implode(" OR c.title=", $tags_list);

您需要在SQL中使用以下where子句:

AND (c.title = 'mexican' OR c.title = 'restaurants')

如果要绑定参数,则必须做更多的工作。
喜欢:

AND (c.title = :title_1 OR c.title = :title2)

您可以使用以下代码分配值:

$title_1 = $tags_list[0];
$title_2 = $tags_list[1];

$stmt->bindParam(':title_1', $title_1);
$stmt->bindParam(':title_2', $title_2);