I'm trying to get the value from the database with this query
$vouchers = MerchantVoucher::where([
'merchant_id' => $this->merchant->id,
'code' => $voucherCode
])
->whereRaw("
(
(valid_from between '{$voucherValidFrom}' and '{$voucherValidTo}' ) ||
(valid_to between '{$voucherValidFrom}' and '{$voucherValidTo}')
)"
)
->count();
with this query i got the expected result which it returns one for the number of rows. I tried to Optimize the query using Prepared Statement for this query belows
$vouchers = MerchantVoucher::where([
'merchant_id' => $this->merchant->id,
'code' => $voucherCode
])
->whereRaw("
(
(valid_from between '?' and '?' ) ||
(valid_to between '?' and '?' )
)",
[
$voucherValidFrom,
$voucherValidTo,
$voucherValidFrom,
$voucherValidTo
]
)
->count();
when I use this query it returns 0.
Anyone got explanation for this? thank you in Advance!
Raw Sql Comparison for non PHP user
select count(*) from `merchant_vouchers` where (`merchant_id` = ? and `code` = ?) and
(
(valid_from between '2019-12-03 11:36:35' and '2019-12-10 11:36:35' ) ||
(valid_to between '2019-12-03 11:36:35' and '2019-12-10 11:36:35')
) and `merchant_vouchers`.`deleted_at` is null
Returns 1
select count(*) from `merchant_vouchers` where (`merchant_id` = ? and `code` = ?) and
(
(valid_from between '?' and '?' ) ||
(valid_to between '?' and '?' )
) and
`merchant_vouchers`.`deleted_at` is null
Returns 0
Framework used : Lumen
Database : MySQL
You need to remove the quotes around your placeholders:
valid_from between ? and ?