0

Why this line doesn't work:

$db_Table = "myTable";

$pdo->prepare("INSERT INTO :db_Table VALUES (...

$query->execute(array(
    ':db_Table' => $db_Table,  

Whereas this one works:

$pdo->prepare("INSERT INTO myTable VALUES (...

How can I solve it ?

Geronimo
  • 37
  • 1
  • 1
  • 5
  • 2
    Yu can't use table names, field names or other identifiers as variables in a prepared statement. You'll need to build your basic query by concatenating or otherwise substituting your identifiers, then `prepare` that result. –  Oct 04 '14 at 17:54
  • 1
    Yes but this one do not works too : `$pdo->prepare("INSERT INTO $db_Table`. – Geronimo Oct 04 '14 at 17:55

2 Answers2

0

Tablenames can not be replaced in a PDO Query.

Further information you can find in the following thread Can PHP PDO Statements accept the table or column name as parameter?

Community
  • 1
  • 1
JSB
  • 54
  • 5
0

unfortunately there are no builtin function for binding table names, you have to do it yourself:

$db_Table = "myTable";
$query = $pdo->prepare("INSERT INTO `$db_Table` VALUES (...)");
$query->execute();

But that is still not being escaped, one workaround is to have an array of table, then check if it exist:

$list_of_tables = array('myTable1', 'myTable2', 'myTable3');
if(!in_array($db_Table, $list_of_tables){
  //table does not exist !
}
meda
  • 45,103
  • 14
  • 92
  • 122