PHP PDO – Bind table name? [duplicate]

Is it possible to bind a table name?

No.

You have to whitelist table names. I doubt you want to let a user to browse any table from your database.

And you have to format identifiers manually as well.
There is a tag wiki with example. Why not read it first?

Update:
As you can see, PDO turns out to be inconvenient for real life tasks.
So, you have to have a more intelligent abstraction library to handle MySQL queries.
Here is an example using the safeMysql class, which will make your code dramatically shorter:

class form{
    public function __construct($table){
        global $db;
        return $db->getAll("DESCRIBE ?n", $table);
    }
}

2 notes:

  • I’ve removed the second parameter as there is no code in your function that uses it.
  • NEVER connect in the class. Use an already opened connection instead. Or you will kill your MySQL server with so many connects.

Exclude implemented version

class form {
    public function __construct($table,$skip = array("id")){
        global $db;
        $data = array();
        $res = $db->query("DESCRIBE ?n", $table);
        while($row = $db->fetch($res)) {
            if (!in_array($row['Field'],$skip)) {
                $data[] = $row;
            }
        }
        return $data;
    }
}

However, such class seldom can be used as intended – there are always a lot of exceptions and manual formatting to make it usable.

Leave a Comment