I’m creating a very simple PHP file that searches a table in my SQLite database.
I want it to filter my table according to 2 parameters, min and max, but I want to be able to specify one parameter, both or even none. How do I translate that into a SQL query?
<?php
$db = new PDO('sqlite:database.db');
$min = $_GET['min'];
$max = $_GET['max'];
if($min == '') $min = -1;
if($max == '') $max = -1;
$res = $db->prepare('SELECT * FROM Roteiro WHERE ...');
$res->execute(array(...));
$test = $res->fetchAll();
print_r($test);
?>
The trick is let the condition be satisfied if the value is null. Make sure you pass type null, not some empty string or other falsy value.
The query optimizer should optimize these extra conditions away no problem because its easy for it to see they never vary per row.
an equivalent way to say it
but I prefer the first way.