MySQL SELECT with multiple conditions

Viewed 219

When searching for available cars, I'm trying to SELECT from cars table WHERE the IDs do not include the already booked cars. For that, I used :

$result = $pdo->prepare("SELECT * FROM cars 
WHERE id NOT IN (" . implode(',', $bookedCarIds) . ") 
AND (location = '$fromlocation'  AND fromdate BETWEEN '$fromdate' AND '$todate') 
"); 

$result->execute();
$availableCars = [];
$availableCars = $result->fetchAll();

Which works perfectly fine.

However, the issue arises when there are no already booked cars in the selected location and dates (where $bookedCarsIds is NULL). To deal with this issue, I used the following code, which throws a syntax error.

$result = $pdo->prepare("SELECT * FROM cars 
WHERE id NOT IN (" . implode(',', $bookedCarIds) . ") AND 
(location = '$fromlocation'  AND fromdate BETWEEN '$fromdate' AND '$todate') 
OR WHERE location = '$fromlocation'  AND fromdate BETWEEN '$fromdate' AND '$todate'
");

 $result->execute();
 $availableCars = [];
 $availableCars = $result->fetchAll();

How can I solve this issue by making changes in this MySQL query alone, without altering the rest of my code?

Thank you.

1 Answers

If you are using PDO, you need to create a dynamic WHERE clause with parameters like in this example:

$whereClause = [];
$params = [];
if (!empty($bookedCarIds)) {
    $whereClause[] = 'id NOT IN (?' . str_repeat(', ?', count($bookedCarIds) - 1) . ')';
    $params = $bookedCarIds;
}
if (!empty($fromlocation)) {
    $whereClause[] = 'location = ?';
    $params[] = $fromlocation;
}
if (!empty($fromdate) && !empty($todate)) {
    $whereClause[] = 'fromdate BETWEEN ? AND ?';
    $params[] = $fromdate;
    $params[] = $todate;
}
$whereClause = !empty($whereClause) ? 'WHERE ' . implode(' AND ', $whereClause) : '';

$result = $pdo->prepare("SELECT * FROM cars $whereClause");
$result->execute($params);
$availableCars = $result->fetchAll();
Related