0

I have the following function. I expect it to print the number of rows in the table provided in its argument.

private function getTotalCount($tbl){
    $sql = "SELECT count(*) FROM :tbl ;";
    $sth = $this->db->prepare($sql);
    $sth->execute(array(
        ':tbl' => $tbl
    ));
    $data = $sth->fetch(PDO::FETCH_ASSOC);
    print_r($data);
}

But the function is not printing anything...

When I replace the function to something like this:

private function getTotalCount($tbl){
    $sql = "SELECT count(*) FROM $tbl ;";
    $sth = $this->db->prepare($sql);
    $sth->execute();
    $data = $sth->fetch(PDO::FETCH_ASSOC);
    print_r($data);
}

Then it works fine and print the number of rows.

QUESTION: Why the execute() function not binding the :tbl parameter to $tbl ??

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sharad Saxena
  • 209
  • 1
  • 2
  • 9

1 Answers1

4

Sadly MySQL PDO doesn't accept parameters for SQL keywords, table names, view names and field names. This doesn't really come up in the main manual, but is mentioned a couple of times in comments.

The solution you have in the second piece of code is the workaround, although you may wish to sanitise the table name first (checking against a white list of table names would be ideal). More info: Can PHP PDO Statements accept the table or column name as parameter?

Community
  • 1
  • 1
John C
  • 8,223
  • 2
  • 36
  • 47