What I'm Trying to Do
I have a SQL table that has a list of job opportunities for a client's website.
I am trying to create a search form but not all the fields will necessarily be filled in.
The possible values are:
title
= the title of the job
location
= the location of the job
sal1
= the bottom bracket of the desired salary
sal2
= the top bracket of the desired salary
The Code
$query = 'SELECT * FROM `jobs`';
if($_GET['title']!='') $query.= ' AND `title` LIKE %'.$_GET['title'];
if($_GET['location']!='') $query.= ' AND `location`='.$_GET['location'];
if($_GET['sal1']!='') $query.= ' AND `sal1`>='.$_GET['sal1'];
if($_GET['sal2']!='') $query.= ' AND `sal2`<='.$_GET['sal2'];
$stmt=$dbh->prepare($query.' ORDER BY `date` DESC');
$stmt->execute();
The Issue
On paper this method should work, but I would prefer to use prepared statements. The only method of doing this seems to be using mysql_real_escape_string()
on each $_GET
variable, as I can't figure out how to use execute(array($val1,$val2...))
when I don't know how many variables are in use.
If possible, how can I utilised prepared statements to sanitize the $_GET
variables?