I’m using PDO in php and as such can’t escape table names or column names using prepared statements. Would the following be a foolproof way to implement it myself:
$tn = str_replace('`', '', $_REQUEST['tn']);
$column = str_replace('`', '', $_REQUEST['column']);
$sql = "SELECT * FROM `tn ` WHERE `column` = 23";
print_r(
$pdo->query($sql)->fetchAll()
);
Or is there still some avenue that this can be attacked?
You can use a dynamic white list by asking the database what columns are valid for a given database table. It’s an additional sql query, but safety is good.
Fetch the results of that and then just make sure all the dynamic column names are in the result set.
I believe views are included in
INFORMATION_SCHEMA.COLUMNS, so it should all just plain work.Then just use backticks around the validated column names when assembling the dynamic sql(I assume you use purely ascii column names, otherwise you potentially have additional considerations).