我一直在读这个:
How can I prevent SQL injection in PHP?
我正在考虑使用这个白名单策略为CRUD创建非常动态的mysql语句。
所以我的想法是构建4个函数,buildSelectStatement,buildInsertStatement,buildDeleteStatement,buildUpdateStatement,每个函数都会帮我构建sql语句。例如," buildSelectStatement"将采取以下论点:
$ choices,$ whitelist_selects,$ where,$ whitelist_where,$ orders,$ whitelist_orders,$ order_syntax,$ whitelist_order_syntax,例如:
$whitelist_select = array("id", "username", "hashed_password", "creation_date", "any other columns in my table"); //all columns in table
$selects = array("id", "username"); //contains fields I want to select
$whitelist_orders = array("creation_date");
$orders = array("creation_date");
$whitelist_order = array("id", "username", "creation_date"); //fields that can be sorted
$order_syntax = "DESC";
$whitelist_order_syntax = array("ASC", "DESC");
$where = ...
... ...
然后在函数内部我将使用array_search来比较$ whitelist_select和$ choices,$ whitelist_orders对$ orders等,以帮助我构建一个动态语句,如:
SELECT `id`, `some_field` FROM user_table WHERE `username` = :username
SELECT `hashed_password` FROM user_table ORDER BY creation_date DESC
然后我将创建一个泛型函数来获取语句并执行它。即
//I used buildSelectStatement() to get $query as well as $bind_array
protected function getSelectResult($query, $bind_array) {
$this->stmt = $this->dbh->prepare($query);
foreach ($bind_array as $param=>$value) {
$this->stmt->bindValue($param, $value, findBindType($value));
}
...
//execute
//then return result
}
这样安全吗?有什么我应该担心的吗?