0

I am populating a Select with data from my database (A SQL Query). The options, for example are:

All Employees
Jack
Joe
Larry
Bob

Now the text All Employees is obviously not an actual employee name, so how would I alter my query based off the value of the Select add a where clause to my sql query?

Obviously $selectedOption = $_POST['testingselect']; would store the selected value in the variable $selectedOption and I could write my Where clause to read (hypothetical)

$SQL = "Select * from goneaz where firstname = $selectedOption"

However, if $selectedOption = All Employees nothing would be returned. How can I add dynamically add in my SQL Statement that (pseudocode) if $selectedOption = All Employees Then SQL = "Select * FROM goneaz. If $selectedOption <> All Employees THEN SQL = "Select * FROM goneaz where firstname = $selectedOption

1 Answer 1

2

All you need to do is concatenate the WHERE clause if the $selectedOption <> All Employees.

$SQL = 'SELECT * FROM goneaz';
if( $selectedOption != 'All Employees' ) {
    $SQL .= " WHERE firstname = '$selectedOption'";
}

//Execute the query
Sign up to request clarification or add additional context in comments.

4 Comments

Minor mod, just so it works properly. Hope you dont mind
@RiggsFolly Thanks for the edit. I completely forgot the quotes '' lol
Simple string concatenation. I was overcomplicating it!
@BellHopByDayAmetuerCoderByNigh It happens. Sometimes all you need is a 5 minute break and everything comes back to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.