I’m playing around with prepared statements in PHP/PDO. The basic queries work fine, passing a value to the WHERE clause:
$stmt = $db->prepare( 'SELECT title FROM episode WHERE id=:id' );
$stmt->bindParam( ':id', $id, PDO::PARAM_INT );
$id = 5;
$stmt->execute();
However I have a situation where I need to pass variables for the field names. This query (with appropriate binding) works fine:
SELECT :field FROM episode WHERE id=:id
This one gives an error:
SELECT title FROM :field WHERE id=:id
This one doesn’t give an error, but returns no rows:
SELECT title FROM episode WHERE :field=:id
So, what things should work in prepared statements? Can I ‘parameterize’ field names, table names and so on?
You cannot parameterize table names, column names, or anything in an
INclause (thanks to c0r0ner for pointing out theINclause restriction).See this question, and subsequently this comment in the PHP manual.