php在pdo查询中使用或变量

时间:2015-01-11 17:38:43

标签: php mysql pdo

我无法在任何地方找到类似的问题所以我想我会问,是否可以使用包含|| php运算符的变量。

例如;

if ($regionID == 9) {
    $location = 'Car' || 'Bus' || 'Plane' || 'Train' || 'Bike' || 'Van';
} else {
    echo 'something went wrong';
}

    $sql=$conn->prepare("SELECT * FROM transport WHERE location = :location AND status = 2 ORDER BY ref LIMIT :limit OFFSET :start");
    $sql->bindValue(':location', $location, PDO::PARAM_STR);

该查询抛出;

PHP Catchable fatal error:  Object of class PDOStatement could not be converted to string

我不知道是不是因为位置变量中的OR运算符,以及是否可以这样使用。

2 个答案:

答案 0 :(得分:1)

你可能想要放

'Car' OR 'Bus' OR 'Plane' OR 'Train' OR 'Bike' OR 'Van'
在您的查询中

。根据您的设计,更好的方法是:

if($region == 9)
    $vehicles = array('Car', 'Bus', 'Plane', 'Train', 'Bike', 'Van');
else { echo 'Something went wrong'; }

    $sql=$conn->prepare("SELECT * FROM transport WHERE location IN :location AND status = 2 ORDER BY ref LIMIT :limit OFFSET :start");
    $sql->bindValue(':location', implode(",", $vehicles));

我还没有测试过,但我认为可行。否则,您可以通过字符串连接将其直接放入查询中,因为这看起来不像可以被篡改的数据。

答案 1 :(得分:0)

$locations需要是一个数组,现在的方式是布尔值:

$locations= array('Car', 'Bus', 'Plane', 'Train', 'Bike', 'Van');

然后将代码调整为:

$sql ='
SELECT * 
FROM   transport 
WHERE  location IN (:location) 
       AND status = 2 
ORDER  BY ref 
LIMIT  :limit offset :start 
';
$sth = $db->prepare($sql);
$sql->bindValue(':location', implode(",", $locations), PDO::PARAM_STR);
...