I would like the users to choose which fields they want to see and which they do not want to see.
Table: Companies(cid, cname, state, project_manager, site_supervisor, elec_engg, mech_engg, hydraulics, …..)
Note: All the columns from project_manager to the last column have the value ‘Yes/No’
Lets say the user wants to find the companies that have Project managers and electrical engineers in NSW.
The Query will be:
Select cid, cname, project_manager, elec_engg
from companies
where state='NSW'
AND project_manager='Yes'
AND elec_engg ='Yes';
I was wondering how can I make this search dynamic. Displaying all job titles in a HTML form and having check boxes next to each job title and with search button. Something like below.
Query:
select cid, cname, (dynamic user input of columns)
from companies
where state="NSW"
AND Dynamic input column1 ='Yes'
and Dynamic input column2 ='Yes'
AND Dynamic input column3 ='Yes'.....
AND Dynamic input columnn ='Yes';
I’m assuming you’re just ANDing all the parameters together. If you can set the name for each HTML the elements in the form exactly what you expect for the column name this should work. When you get the post back (assuming search submits the form as a post), you can loop through the post values. I’d create an array of valid columns to check against as a whitelist to avoid ever having a broken query.
Here’s an example using oldschool mysql escaping or you to get the idea, but I’d really use PDO with prepared statements to populate the values of the query. The key is to protect both your where parameters and values when dynamically creating SQL. Shoot me a message if you’re using PDO and would like to see that, but this will give you a place to start:
You can also add a loop check for just values of ‘Yes’ and exclude ‘No’ values…
As noted below in a comment mysql_escape_string($value) is bad… no doubt, to do this correctly and safely with prepared statements and pdo you would change the code to:
$sql = ‘SELECT cid, cname, project_manager, elec_engg FROM companies ‘;
$whereClause = null;
Both the prepared statements on the values and the whitelist on the parameter values will make this query safe.