0

I have a little problem that i can't explain :

I have my query working with pdo in php like this :

 $table = "Potatatoe";
    $sql = $pdo->prepare('SELECT  * FROM EATABLES WHERE FOOD = ? ');
    $sql->execute(array($table));
    $data = $sql->fetchAll(PDO::FETCH_ASSOC);
    var_dump($data);exit;

The vardump will return some datas.

But my problem is i have an array of tables

$tables = array("T_tab1", "T_tab2", "T_tab3", ..);

And i would like to run a query SELECT * FROM [eachtable in the array] So i have :

$sql = $pdo->prepare('SELECT  * FROM ? ');
            $sql->execute(array($table));
            $data = $sql->fetchAll(PDO::FETCH_ASSOC);
            var_dump($data);exit;

with $table which is from an foreach on $tables

So why i can't have something like this "SELECT * FROM ?" with ? equals to a string ?

Any help would be appreciated !

sleakerz
  • 169
  • 19
  • 3
    Table and Column names cannot be replaced by parameters in PDO – Saty Jul 27 '16 at 11:35
  • 1
    `PDO` will **quote** parameters if they are strings (or floats). That means your query becomes `SELECT * FROM 'potatoes'` -> that's invalid SQL. You never pass table names as parameters, **only values**. – Mjh Jul 27 '16 at 11:36
  • How i should do to make SELECT * FROM "TABLE" for each table in my array ? – sleakerz Jul 27 '16 at 11:37
  • 1
    Foreach your tables and create a statement for each of them, bind what you have to and execute. There's no need to complicate really. – Mjh Jul 27 '16 at 11:38
  • Thanks, so i will make a $query = "SELECT * FROM" . $param; and then execute this query ! Thanks for your help guys ! – sleakerz Jul 27 '16 at 11:40
  • @Mjh With native prepared statements, nobody will quote anything. The database will see all placeholders as *data values* natively. However the database also wants to, well, ***prepare*** the query, which means it wants to establish a query plan. It cannot do that if it doesn't know the table name. Placeholders are for *values*, period; not structural information like table names. – deceze Jul 27 '16 at 11:40
  • @deceze you really like to nitpick and correct the things no one asked about, right? How about I dig up the source code where MySQL does this and prove you wrong? For all purposes, be it PDO performing quoting or MySQL treating parameters the way it has to, what's easier to understand is what I wrote. Whatever the case, only column values go through the statement as parameters, which apparently I demonstrated that I know. Unless you want to correct that too. – Mjh Jul 27 '16 at 11:44

0 Answers0