PHP PDO - Binding Table Names
In PHP Data Object (PDO), is it possible to bind a table name to a prepared statement?
Answer:
No, it is not possible to bind a table name in PDO.
Binding a table name introduces security risks as it allows users to access any table in the database. It is recommended to whitelist table names to ensure only authorized tables can be queried.
Alternative Approach:
To safely access table metadata, consider creating a parent class for your table classes, such as:
abstract class AbstractTable { private $table; private $db; public function __construct(PDO $pdo) { $this->db = $pdo; } public function describe() { return $this->db->query("DESCRIBE `$this->table`")->fetchAll(); } }
Then, create a specific class for each table, such as:
class MyTable extends AbstractTable { private $table = 'my_table'; }
Using this approach, you can access table metadata safely:
$pdo = new PDO(...); $table = new MyTable($pdo); $fields = $table->describe();
The above is the detailed content of Can You Bind Table Names in PHP PDO Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!