Home > Article > Backend Development > Can you Bind a Table Name in PHP PDO?
Query:
Can you bind a table name in PHP PDO?
Issue:
Attempting to bind a table name using bindValue() results in an error. The issue arises when trying to dynamically set the table name through user input.
Solution:
No, it's not possible to bind a table name directly.
This is due to security concerns, as it could allow users to access arbitrary tables in the database. Instead, it is recommended to:
Secure Implementation with Abstraction Layer:
To create a secure class for accessing table data, follow these steps:
abstract class AbstractTable { private $table; private $pdo; public function __construct(PDO $pdo) { $this->pdo = $pdo; } public function describe() { return $this->pdo->query("DESCRIBE `" . $this->table . "`")->fetchAll(); } } class SomeTable extends AbstractTable { private $table = 'sometable'; }
Now, use the class to access the table data safely:
$pdo = new PDO(...); $table = new SomeTable($pdo); $fields = $table->describe();
The above is the detailed content of Can you Bind a Table Name in PHP PDO?. For more information, please follow other related articles on the PHP Chinese website!