How to dynamically build queries with PDO

I am using PDO and want to do something like this:

$query = $dbh->prepare("SELECT * FROM :table WHERE :column = :value");
$query->bindParam(':table', $tableName);
$query->bindParam(':column', $columnName);
$query->bindParam(':value', $value);

Will PDO allow me to bind the table name and the column name like this? It seems to allow it, but it puts quotes around my parameters even if I use PDO::PARAM_INT or PDO::PARAM_BOOL as the data type.

If this won't work, how can I safely escape my variables so that I can interpolate them in the query?


Unfortunately, you can't bind parameters by column names.

What you could try is to dynamically create your SQL command:

$sql = "SELECT * FROM $tableName WHERE $columnName = :value";
$query = $dbh->prepare($sql);
$query->bindParam(':value', $value);

Just make sure to sanitize your parameters/variables if they are coming from elsewhere, to prevent SQL Injection. In this case, $value is safe to a degree but $tableName and $columnName are not -- again, that is most especially if the values for these variables are not provided by you and instead by your users/vistors/etc...

One other thing; please avoid using * and name your columns instead... See some reasons why:

http://www.jasonvolpe.com/topics/sql/

Performance issue in using SELECT *?

See other similar posts here:

Why doesn't binding parameter in ORDER BY clause order the results?

How do I set ORDER BY params using prepared PDO statement?