如何在OR上选择OR查询条件?

时间:2013-05-17 23:03:55

标签: php sql pdo

$sql = "SELECT message FROM sale WHERE seller_id=? && payment_date=? && bank=?";

$q = $conn->prepare($sql);
$result = $q->execute(array($user_id, $paydate, bank1|| bank2|| bank3));

如何纠正“bank1 || bank2 || bank3”的错误?

2 个答案:

答案 0 :(得分:2)

$sql = "SELECT message FROM sale WHERE seller_id=? AND payment_date=? 
    AND bank IN (?, ?, ?)";

$q = $conn->prepare($sql);
$result = $q->execute(array($user_id, $paydate, $bank1, $bank2  $bank3));

如果您拥有动态数量的银行(例如,在数组$ bank中):

$sql = "SELECT message FROM sale WHERE seller_id=? AND payment_date=? ";

$values = array($user_id, $paydate);

if ($banks) {
  $sql .= " AND bank IN (" . implode(",",array_fill(0,count($banks),"?")) . ")";
  $values = array_merge($values, array_values($banks));
}

$q = $conn->prepare($sql);
$result = $q->execute($values);

PS:我建议在SQL中使用ANDOR,而不是&&||。在标准SQL中,||是字符串连接运算符。你应该养成编写标准SQL的习惯。

答案 1 :(得分:0)

将数组保存在数组中,然后将数组放在执行语句中。但您也必须将&& bank=更改为&& bank in (),因为您将查询动态数量的银行。