0
$tconn = new PDO('mysql:host='.WW_HST.';dbname='.WW_DB, WW_USR, WW_PS);
$res = $tconn->prepare('SELECT * FROM :tbl');
$res->execute(array(':tbl'=>"ugb"));  

When I use this code to draw data from the 'ugb' table, I get the following error:

'PDOException' with message '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 ''ugb'' at line 1'

So it's correctly substituting :tbl for 'ugb' but whether I do a bind or just execute with an array, I always get an error. It works fine if I just do SELECT * FROM ugb though.

How can I correct this problem?

George Cummins
  • 28,485
  • 8
  • 71
  • 90
NARKAN
  • 17
  • 1

2 Answers2

2

PDO does not allow you to set variables in FROM.

You only could add table name in query string.

I usually do by this way:

$allowedTables = array('first', 'second', 'third');
if(in_array($tblName, $allowedTables)) {
  $$res = $tconn->prepare("SELECT * FROM $tblName");
}
Vlad Bereschenko
  • 338
  • 1
  • 3
  • 11
-2

I don't think that PDO will allow you to bind a parameter to the FROM statement. You could try manualy escaping the table name parameter and after that adding it to the query like this:

$table = "ugb";
$tconn = new PDO('mysql:host='.WW_HST.';dbname='.WW_DB, WW_USR, WW_PS);
$res = $tconn->prepare('SELECT * FROM '. $tconn->quote($table));
$res->execute();

Hope this helps.

lexmihaylov
  • 717
  • 3
  • 8