Columns and expressions in the WHERE clause must be fixed at the time you prepare the query. There's no way to parameterize columns or expressions in SQL.
The way most people solve this problem is by writing application code to add terms to your WHERE clause based on application logic and variables. In other words, append fragments of SQL syntax to a string inside code constructs like if ()
. The specific methods for doing this depend on the programming language you're using.
To help in this technique, sometimes frameworks provide a query builder API. For example, I worked on the Zend Framework, which includes a class called Zend_Db_Select. It helps you append terms to a query. The result is simply a string, which you can then prepare as an SQL statement.
I don't work on Drupal, but I see in their online manual they have an API method for adding terms to an SQL WHERE clause, similar to what I was describing above.
I suppose that if you had a PHP associative array of key/value pairs such that the key is the column name and the value is the value to search for, you could do this:
<?php
$query = ... // create the query object
$search_conditions = array(
name => "username",
date => "today",
title => "hello"
);
foreach ($search_conditions as $col => $val) {
$query = $query->condition($col, $val, "=");
}
$query->execute();
The manuals says:
A conditional object consists of one or more conditional fragments that will all be joined by a specified conjunction. By default, that conjunction is AND.
So you can add zero, one, or more conditions to the query, and it keeps track of them, as if you had written the following:
WHERE name = :name AND date = :date AND title = :title
When it is time to execute the query, it automatically passes the values you gave ("username", "today", "hello") for those parameter placeholders.