zac1987
zac1987

Reputation: 2777

How to put OR on pdo select query where condition?

$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));

how to correct the mistake of "bank1 || bank2 || bank3" ?

Upvotes: 2

Views: 1330

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562378

$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));

If you have a dynamic number of banks (e.g. in an array $banks):

$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: I recommend using AND and OR in SQL instead of && and ||. In standard SQL, || is the string concatenation operator. You'd be wise to develop the habit of writing standard SQL when you can.

Upvotes: 2

digitai
digitai

Reputation: 1842

Hold the banks inside an array and then place the array inside the execution statement. But also you must change && bank= to && bank in (), due to the dynamic amount of banks you'll query.

Upvotes: 0

Related Questions