简体   繁体   中英

safely escaping table names/column names

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.

select COLUMN_NAME 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_SCHEMA = :databaseName
  and TABLE_NAME = :tableName

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM