V
V
Vlad Gromov2019-07-22 02:37:06
PHP
Vlad Gromov, 2019-07-22 02:37:06

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.
5d34f55c17540836454703.png
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;
        }

The function theoretically works if the user, when entering data into the filter, specified the price range "from" and "to".
But if $from and $before do not come to the function, then the SQL query crashes.
The question is how to make it so that if the user did not specify a price range, the SQL query would not crash, but simply show all the products that are in stock.
There was an idea to specify function search($from =0 , $before =9999999999 ) {...}, but this is somehow rude, perhaps there is a more elegant solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey, 2019-07-22
@Vikkiners

$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 question

Ask a Question

731 491 924 answers to any question