nanjero05 nanjero05 - 1 year ago 60
SQL Question

PHP/SQL How can I make an optional WHERE condition

I am currently using this sql statement:

$sql = "SELECT rid, beds, orientation, price FROM rooms
WHERE (beds = $nOfBeds) OR (beds = $nOfBeds AND orientation = '$rOrientation')";

$rOrientation is suppose to be an optional value. a user can make a selection on it or not. How can i make a where statement to take into account both selections where a user selects an orientation or otherwise.

currently it is only showing results based on number of beds and ignoring whether i select an orientation or not

Answer Source

Following the same syntax:

$sql = "SELECT rid, beds, orientation, price FROM rooms
        WHERE beds = $nOfBeds";

if (!empty($rOrientation)) {
    $sql .= " AND orientation = '$rOrientation'";

Note that using prepared statements and/or good input validation is important.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download