php - 如何将多个 GET 参数连接到准备好的语句中
问题描述
我正在开发一个地理定位应用程序,并希望根据用户的标签返回半径结果
$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;
}
}
?>
解决方案
问题在这里:
$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);
推荐阅读
- sql - 创建表时清空表
- php - Laravel 中的测试 - 每个文件只运行一次数据库迁移,而不是每个单独的测试
- javascript - 如何让 Django 代码中的 Javascript 监听并响应前端的点击事件?
- amazon-web-services - Presigned S3 url 在过期时间后有效
- sql-server - 如何获取在 MS SQL 中执行的 UPDATE 语句
- javascript - 仅当在节点 js 中完成一个方法调用时,我如何才能返回响应
- ios - 带有滑动操作的 RxSwift TableView
- sas - 如何在 SAS 中创建嵌套行?
- ios - 如何在 Swift 包管理器中添加 Reality 文件?
- react-native - React-navigation - 嵌套导航器中的 goBack 行为(抽屉内的堆栈)