How to dynamically build queries with PDO

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?

Leave a Comment