Can Parameters Substitute Table or Column Names in PHP PDO Statements?
It is impossible to pass table names as parameters to prepared PDO statements. Consider the following code that attempts to do so:
$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1'); if ($stmt->execute(array(':table' => 'users'))) { var_dump($stmt->fetchAll()); }
This approach will result in an error, as table and column names cannot be replaced by parameters.
Safe Insertion of Table Names into SQL Queries
To safely insert table names into SQL queries, an alternative approach is necessary. Avoid directly inputting user input into the query, such as:
$sql = "SELECT * FROM $table WHERE 1"
Instead, consider filtering and sanitizing the input. One method involves passing shorthand parameters to a function that will dynamically execute the query. A switch() statement can then be employed to whitelist valid table names. For example:
function buildQuery( $get_var ) { switch($get_var) { case 1: $tbl = 'users'; break; } $sql = "SELECT * FROM $tbl"; }
By omitting a default case or using one that displays an error message, you guarantee that only desired values will be utilized.
The above is the detailed content of Can PHP PDO Prepared Statements Use Parameters for Table or Column Names?. For more information, please follow other related articles on the PHP Chinese website!