-3

Problem

I get a PDO syntax error when running a PDO statement where the table name is parametrized, like in

$sql = 'DELETE FROM :table_name';
$query = $this->db->prepare($sql);
$query->execute(array(':table_name' => "mytable"));

I could reproduce the problem with SELECT etc., so it's a general issue. I tried to write it with backticks, with database name in front of it, a combination of both etc, nothing works.

Question

How to do this ?

Sliq
  • 15,937
  • 27
  • 110
  • 143

2 Answers2

5

You cannot parameterize table names, column names, or anything in an IN clause (it'll have to be bound separately). See this comment on php.net.

See also: Can PHP PDO Statements accept the table or column name as parameter?

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • I thought you could use bound parameters in an IN clause, so long as you bind each one seperately? Ie `IN (?)` won't work, but `IN (?, ?, ?)` should. – andrewsi Oct 16 '13 at 13:34
  • @andrewsi: you're right. I've updated the answer to avoid confusion. – Amal Murali Oct 16 '13 at 13:47
  • 1
    Is there a PDO maintainer that could fix this? It's a very common question and the solutions are always worryingly hacky due to a lack of an official method to do it. – tadman Oct 16 '13 at 14:28
0

You can't parameteterize table name with PDO and MySQLi prepared statements, because SQL server needs basic information to prepare the query before executing actual query.

Jason OOO
  • 3,567
  • 2
  • 25
  • 31