I have a SQL table with model year from and model year to, in filter I need to select only one parameter year and I want to get all models which are in that year gap.
Seem like you don't have put the full request, but you should be able to do something with this :
WHERE
$year >= `from`
AND $year <= coalesce(`to`, 9999)
The coalesce()
is here in case you don't have a to
date but a NULL instead (still in production).
Here is the full version : (As I really can't stand mysqli_*
function, and they are not well suited/secure for this use case, This is a PDO solution)
setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
// error SQL as object
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET CHARACTER SET utf8");
} catch (Exception $e) {
echo ''.$e->getMessage().'
'."\n";
}
// default parameters
$param = array();
$sql = "SELECT * FROM `cars` WHERE `id` != '' ";
if(!empty($_POST['make'])){
$param[':make'] = $_POST['make'];
$sql .= 'AND `make` = :make ';
}
if(!empty($_POST['model'])){
$param[':model'] = $_POST['model'];
$sql .= 'AND `model` = :model ';
}
if(!empty($_POST['from'])){
$param[':from'] = $_POST['from'];
$sql .= 'AND :from >= coalesce(`from`, 0) AND :from <= coalesce(`to`, 9999) ';
}
// we prepare our request
$stmt = $db->prepare($sql);
// we execute with our parameters
$stmt->execute($param);
while($r = $stmt->fetch()){
echo $r->id.' - '.$r->make.' - '.$r->model.' - '.$r->from;
echo"";
}