Answer the question
In order to leave comments, you need to log in
How to make sure that if the user does not specify a price range, the SQL query does not crash?
Comrades, I ask for help, the following problem arose.
For educational purposes, I am making an "online watch store".
I made a page a la "Yandex-market", where you can send a request to the database using filters to display only such brands / such a price range / with such a case / etc.
As a result, I started by entering a price from / before and wrote something like this function:
function search($from, $before) {
$sql = "SELECT * FROM watches WHERE price > $from AND price < $before";
$stmt = $this->_instance->query($sql);
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
Answer the question
In order to leave comments, you need to log in
$select = 'select * from watches where 1=1';
$binds = [];
if(!empty($from)) {
$select .= ' and from>=?';
$binds[] = $from;
}
if(!empty($before)) {
$select .= ' and before<=?';
$binds[] = $before;
}
$stmt = $this->_instance->prepare($sql);
$stmt->execute($binds);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question