'This is the best way to create a range filter in SQL with php IF statement?
So I want to create a range filter and I wondering if this is the best way to create if statement. Is there cloud go anything wrong?
So here is my code:
$from = "20";
$to = "21";
$bind_value = array();
if ( !empty($from) && !empty($to) && $from < $to ) {
$myquery .= " WHERE rand_number BETWEEN :from AND :to";
$bind_value = array_merge($bind_value, array(
'from'=>"$from",
'to'=>"$to",
));
}
else if (!empty($from) && empty($to)) {
$myquery .= " WHERE rand_number >= :to ";
$bind_value = array_merge($bind_value, array(
'to'=>"$to"
));
}
else if (!empty($to) && empty($from)) {
$myquery .= " WHERE rand_number <= :from ";
$bind_value = array_merge($bind_value, array(
'from'=>"$from"
));
}
else {
$myquery .= "";
}
$stmt = $connpdo->prepare("SELECT * FROM my_table ".$myquery."");
// Bind values
foreach($bind_value as $key=>$search){
$stmt->bindValue(':'.$key, $search,PDO::PARAM_STR);
}
$stmt->execute();
Solution 1:[1]
Mostly it would work the only thing is the last bit would give an error as there is no validator on the end of the query.
the else statement would resolve in:
select * from my_table where rand_number
this errors in sql, to make it correct you would need to remove the where statement completly:
select * from my_table
Besides this you can write the code slighly easier:
if ( !empty($from) && !empty($to) && $from < $to ) {
$myquery .= " WHERE rand_number BETWEEN :from AND :to";
$bind_value = array_merge($bind_value, array(
'from'=>"$from",
'to'=>"$to",
));
}elseif (!empty($from) && empty($to)) {
$myquery .= " WHERE rand_number >= :to ";
$bind_value = array_merge($bind_value, array(
'to'=>"$to"
));
}elseif (!empty($to) && empty($from)) {
$myquery .= " WHERE rand_number <= :from ";
$bind_value = array_merge($bind_value, array(
'from'=>"$from"
));
}
echo $myquery;
The numbers can be strings or integers, this will not matter for the sql statement
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Your Common Sense |
