PDO不能使用?查询OFFSET的参数替换,仅用于数据值

时间:2015-01-14 19:01:34

标签: php mysql arrays pdo

我正在尝试使用?而不是绑定一个值,因为你不能在同一个查询中混合?:binds,我需要使用?对于数组我在查询中崩溃。

//Set values
$limit = 5;
$offset = 2;
$location = array("Cornwall", "Devon", "Dorset", "Norfolk & Suffolk", "Somerset", "Wiltshire");

//Sort the array by adding ?
$qMarks = str_repeat('?,', count($location) - 1) . '?';

//Query using ? because you can't mix them in a query
$location[] = (int)$limit;
$location[] = (int)$offset;
$sql = $conn->prepare("SELECT * FROM adverts WHERE location IN ($qMarks) AND status = 2 LIMIT ? OFFSET ?");
$sql->execute($location);
$adverts=$sql->fetchAll();

这应该将数组中的每个字符串插入到查询中,最后添加$limit& $offset变量。

当我转储查询时,它似乎正在显示,因为我希望它具有每个数组项,然后最后两个用于限制和偏移但不运行;

array(8) { [0]=> string(8) "Cornwall" [1]=> string(5) "Devon" [2]=> string(6) "Dorset" [3]=> string(17) "Norfolk & Suffolk" [4]=> string(8) "Somerset" [5]=> string(9) "Wiltshire" [6]=> int(5) [7]=> int(2) }

这是我在代码中遇到的错误;

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''5' OFFSET '0'' at line 1' in /advert.php:30
Stack trace:
#0 advert.php(30): PDOStatement->execute(Array)
#1 {main}
  thrown in advert.php on line 30

0 个答案:

没有答案