我有以下准备声明:
SELECT `e1`.`field_value` AS `county`,
`e2`.`field_value` AS `venue_type`,
`l`.`ID` AS `listing_id`,
`l`.`ID` AS `id`,
`l`.`user_ID` AS `user_id`,
IF(`l`.`user_ID` > 1, 'b', 'a') AS `flag` ,
COUNT(`img`.`ID`) AS `img_num`
FROM ( `listingsDBElements` `e1`,
`listingsDBElements` `e2`,
`listingsDB` `l` )
LEFT JOIN `listingsImages` `img` ON (`l`.`ID` = `img`.`listing_id`
AND `l`.`user_ID` = `img`.`user_id`
AND `img`.`active` = 'yes')
WHERE `e1`.`field_name` = 'county'
AND `e1`.`field_value` = :county
AND `l`.`ID` = `e1`.`listing_id`
AND `l`.`user_ID` = `e1`.`user_id`
AND `e2`.`field_name` = 'venue_type'
AND `e2`.`field_value` = :venueType
AND `l`.`ID` = `e2`.`listing_id`
AND `l`.`user_ID` = `e2`.`user_id`
AND `l`.`ID` = `e2`.`listing_id`
AND `l`.`user_ID` = `e2`.`user_id`
AND `l`.`active` = 'yes'
GROUP BY `l`.`ID`
ORDER BY `flag` DESC,
`img_num` DESC LIMIT :limit,
:offset
绑定以下参数:
:county => 'Bedfordshire'
:venueType => 'Conference Centre'
:limit => 0
:offset => 12
然后我使用PDO执行Prepared Statement,如下所示:
$vens = $db->prepare($sql);
if($paged)
{
$limit = (int) (($page - 1) * $perPage);
$perPage = (int) $perPage;
$vens->bindParam(':offset', $perPage, PDO::PARAM_INT);
$vens->bindParam(':limit', $limit, PDO::PARAM_INT);
}
foreach($bindings as $key => $value) { $vens->bindParam($key, $value, PDO::PARAM_STR); }
$vens->execute();
while($ven = $vens->fetchObject())
{
$_tpl['venues'][] = new Venue($ven->id);
}
上面总是返回0结果,即使使用$db->rowCount()
,但如果我手动运行查询并替换MySQL中的占位符,则会生成4条记录的预期结果。奇怪的是,我有另一个(几乎相同的)查询运行并计算总行数,并绑定相同的参数如下:
SELECT COUNT(DISTINCT(`l`.`ID`)) AS `total`
FROM ( `listingsDBElements` `e1`,
`listingsDBElements` `e2`,
`listingsDB` `l` )
WHERE `e1`.`field_name` = 'county'
AND `e1`.`field_value` = :county
AND `l`.`ID` = `e1`.`listing_id`
AND `l`.`user_ID` = `e1`.`user_id`
AND `e2`.`field_name` = 'venue_type'
AND `e2`.`field_value` = :venueType
AND `l`.`ID` = `e2`.`listing_id`
AND `l`.`user_ID` = `e2`.`user_id`
AND `l`.`ID` = `e2`.`listing_id`
AND `l`.`user_ID` = `e2`.`user_id`
AND `l`.`active` = 'yes'
以上操作使用:
执行$counter = $db->prepare($countSql);
$counter->execute($bindings);
$counts = $counter->fetchObject();
$counts->total
正确返回4
。任何人都可以建议为什么第一个Prepared Statement通过PDO返回0行,但在手动输入MySQL时工作正常吗?
修改
根据Joachim的评论,还有其他查询可以在限制和偏移的约束参数下正常运行,甚至删除它们也会返回相同的结果。例如,以下查询工作正常:
SELECT `l`.`ID` AS `id`,
IF(`l`.`user_ID` > 1, 'b', 'a') AS `flag`
FROM `listingsDB` `l`
INNER JOIN `listingsDBElements` `e` ON `l`.`ID` = `e`.`listing_id`
WHERE `e`.`field_name` = 'city'
AND `e`.`field_value` = :town
AND `l`.`active` = 'yes'
ORDER BY `flag` DESC LIMIT :limit,
:offset
答案 0 :(得分:1)
基本上,您只能在预备声明中绑定某些类型的事物。
来自MySQL manual:
标记仅在SQL语句的某些位置是合法的。例如,允许在INSERT语句的VALUES()列表中(指定行的列值),或与WHERE子句中的列进行比较以指定比较值。但是,它们不允许用于标识符(例如表名或列名),也不允许指定二元运算符的两个操作数,例如=等号。后一种限制是必要的,因为无法确定参数类型。通常,参数仅在数据操作语言(DML)语句中是合法的,而在数据定义语言(DDL)语句中不合法。
请注意,LIMIT和OFFSET不在允许的位置列表中。