2014-06-23 20 views
2

我有一个查询计算是基于此文档的点的一定半径内的对象:http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/perl的错误传递时DBI->执行值IN子句

它的工作原理很漂亮,但是我想只搜索那些特定类型的对象,这会导致问题;

的代码看起来是这样的:

my $sql = "SELECT * 
FROM (
SELECT b.*, pr.postcode, pr.prize, pr.title, pr.collection, pr.redeemed, pr.delivery, pr.archived, bt.category, 
     p.radius, 
     p.distance_unit 
       * DEGREES(ACOS(COS(RADIANS(p.latpoint)) 
       * COS(RADIANS(b.lat)) 
       * COS(RADIANS(p.longpoint - b.lng)) 
       + SIN(RADIANS(p.latpoint)) 
       * SIN(RADIANS(b.lat)))) AS distance 
    FROM bubbles AS b, bubble_prizes AS pr, bubble_types AS bt 
    JOIN ( /* these are the query parameters */ 
     SELECT ? AS latpoint, ? AS longpoint, 
       ? AS radius,  ? AS distance_unit 
    ) AS p 
    WHERE b.lat 
    BETWEEN p.latpoint - (p.radius/p.distance_unit) 
     AND p.latpoint + (p.radius/p.distance_unit) 
    AND b.lng 
    BETWEEN p.longpoint - (p.radius/(p.distance_unit * COS(RADIANS(p.latpoint)))) 
     AND p.longpoint + (p.radius/(p.distance_unit * COS(RADIANS(p.latpoint)))) 
    AND pr.bubble = b.id 
    AND b.type IN ? 
    AND b.type = bt.type 
) AS d 
WHERE distance <= radius 
ORDER BY distance";  

然后我做

my $points = $y->dbh->prepare($sql); 
$results = $points->execute($lat, $lng, $rad, $units, '(type1, type2)'); 

位置 '(TYPE1,TYPE2)' 应该传递给

b.type IN ? 

(这是近SQL的底部)。

我已经想尽办法,我能想到的逃离这个字符串,以便它的作品(包括很多方面是清楚的疯狂,但我越来越绝望)INC

'(type1, type2)' 
'\(\'type1\', \'type2\'\)' 
'(\'type1\', \'type2\')' 
"('type1', 'type2')" 

等(我已经试过这么多的东西,我甚至不能全部记住它们。)

无论我怎么努力,我得到的形式

DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(type1, type2)' 
    AND b.type = bt.type 
) AS d 
WHERE distance <= radius' 

的SQL错误取决于我如何试图逃脱字符串,t他的错误信息稍有不同,但总是与sql的相同部分有关。

我现在在想,转义不是我的问题,我错过了一些关于执行的东西。如果我在DB中运行代码,它可以正常使用IN语句,即b.type IN('type1','type2')正常工作。

有人能够启发我吗?我该如何做到这一点?

感谢

回答

2

您将需要IN (...)语句中使用占位符。​​的整个点是为了避免SQL注入,并且你基本上试图在那里注入SQL。你可以这样做一个动态的占位符列表:

my @types = qw(type1 type2); 
my $placeholders = join ", ", ("?") x @types; 
my $sql = "... 
     b.typeID IN ($placeholders) 
    ..."; 
my $points = $y->dbh->prepare($sql); 
$results = $points->execute($lat, $lng, $rad, $units, @types); 
+0

这样做了,谢谢 – mark