nanjero05
nanjero05

Reputation: 111

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

Upvotes: 0

Views: 73

Answers (1)

Julie Pelletier
Julie Pelletier

Reputation: 1716

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.

Upvotes: 1

Related Questions