Home > Software engineering >  sql query WHERE equal or empty
sql query WHERE equal or empty

Time:01-27

What is the proper way to do a an sql query in this case. For example: The only problem is sometimes they may not select bedroom, so we need to pull up all bedrooms and sometimes we need to pull up only 3 bedrooms. So bedrooms is sometimes empty.

$bedroom = $_REQUEST['bedroom'];

SELECT * FROM apartments WHERE bedrooms = '$bedroom'

CodePudding user response:

SELECT * FROM apartments WHERE ('$bedroom' = '' OR bedrooms = '$bedroom')

Note that you also shouldn't substitute variables directly into the query, you should use a prepared statement with parameters. See How can I prevent SQL injection in PHP?. So it should actually be:

SELECT * FROM apartments WHERE ('$bedroom' = ? OR bedrooms = ?)
  •  Tags:  
  • Related