0

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 = ?'

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127

2 Answers2

0

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-3

You need to bind the parameters like this:

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

Source (see Example #2)

tim
  • 3,191
  • 2
  • 15
  • 17
  • Close, but no. You can't bind table names in PDO even though arguably this is a massive oversight. – tadman Aug 27 '13 at 18:59