Q:

An alternative to SQL concatenation for search options?

I'm a novice programmer, and I've inherited an application designed and built by a person who has now left the company. It's done in PHP and SQL Server 2008R2. In this application, there's a page with a table displaying a list of items, populated from the database, with some options for filters in a sidebar - search by ID, keyword, date etc. This table is populated by a mammoth query, and the filters are applied by concatenating them into said query. For example, if someone wanted item #131:
$filterString = "Item.itemID = 131";
$filter = " AND " . $filterString;

SELECT ...
FROM ...
WHERE...
$filter

The filter is included on the end of the URL of the search page. This isn't great, and I'm fairly sure there are some SQL injection vulnerabilities as a result, but it is extremely flexible - the filter string is created before it's concatentated, and can have lots of different conditions: E.g.$filterString could be "condition AND condition AND coindtion OR condition".
I've been looking into Stored Procedures, as a better way to counter the issue of SQL Injection, but I haven't had any luck working out how to replicate this same level of flexibility. I don't know ahead of time which of the filters (if any) will be selected. 
Is there something I'm missing?

A:

Use either Mysqli or PDO which support prepared/parameterized queries to battle sql injection. In PDO this could look something like this
$conditions = '';
$params = array();

if(isset($form->age)) {
  $conditions .= ' AND user.age > ?'
  $params[] = $form->age;
}

if(isset($form->brand)) {
  $conditions .= ' AND car.brand = ?'
  $params[] = $form->brand;
}

$sql = "
  SELECT ...
  FROM ...
  LEFT ...
  WHERE $conditions
  ";

$sth = $dbh->prepare($sql);
$sth->execute($params);

$result = $sth->fetchAll();

From the manual:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

http://no1.php.net/manual/en/pdo.prepare.php

