Using question mark instead of table name in PDO prepared statements

1.2k views Asked by At

I need to know can I use question marks (?) in PDO prepared statements as table name or not.

$table = $_POST['table'];
$id = $_POST['id'];
$sql = "UPDATE ? SET priority = priority + 1 WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($table,$id));

I'm getting this error:

Warning: PDO::prepare() [pdo.prepare]: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? SET priority = priority + 1 WHERE id = ?'

2

There are 2 answers

1
tim On

You need to bind the parameters like this:

$q->bindParam(1, $table);
$q->bindParam(2, $id);

Source (see Example #2)

0
Your Common Sense On

Aside from that simple problem, there is another one - your code smells of bad database design. In a properly planned database you would never need to receive a table name via POST request.

Most likely you are using multiple tables where you have to use only one.