According to the PHP Documentation PDO::prepare() adds quotes to all your parameters so that you don't have to worry about doing it:
根据PHP文档PDO :: prepare()为所有参数添加引号,这样您就不必担心这样做了:
"The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible)."
“不需要引用预处理语句的参数;驱动程序自动处理这个。如果应用程序专门使用预准备语句,开发人员可以确保不会发生SQL注入(但是,如果查询的其他部分正在用非转义输入构建,SQL注入仍然可行。)“
The problem with this for me is the way I am building my queries and my database structure. Usually the FROM part of an SQL Statement wouldn't need to be parametrized because the Table probably would be defined by direct user input. However with my code that is the case in some places and thus I feel more comfortable with the parametrized version.
这对我来说的问题是我构建查询和数据库结构的方式。通常,SQL语句的FROM部分不需要参数化,因为表可能由直接用户输入定义。但是我的代码在某些地方就是这种情况,因此我对参数化版本感觉更舒服。
SELECT * FROM ? WHERE ?=?
as opposed to SELECT * FROM tablename WHERE ?=?
而不是SELECT * FROM tablename WHERE?=?
So my question is this, is it possible to prevent my PDO Object from adding the quotes around the FROM parameter so that I don't get SQL errors thrown in my face? Or do I have to do this in a different manner.
所以我的问题是,是否有可能阻止我的PDO对象在FROM参数周围添加引号,以便我不会在我的脸上抛出SQL错误?或者我必须以不同的方式这样做。
2 个解决方案
#1
4
The placeholders in prepared statements are for values only. The only way to insert dynamic table names is to do it yourself
预准备语句中的占位符仅用于值。插入动态表名的唯一方法是自己动手
"SELECT FROM `".$table."` WHERE `".$column."` = ?"
#2
2
@KingCrunch is mostly correct in his answer. You should really escape the string on your own. Something like this should protect against most injections:
@KingCrunch在答案中大多是正确的。你应该自己逃避字符串。这样的事情可以防止大多数注射:
//make sure $table and $column only contain alphanumeric chars
$table = preg_replace("/[^A-Za-z0-9]/", '', $table);
$column = preg_replace("/[^A-Za-z0-9]/", '', $column);
$query = "SELECT FROM `{$table}` WHERE `{$column}` = ?"
#1
4
The placeholders in prepared statements are for values only. The only way to insert dynamic table names is to do it yourself
预准备语句中的占位符仅用于值。插入动态表名的唯一方法是自己动手
"SELECT FROM `".$table."` WHERE `".$column."` = ?"
#2
2
@KingCrunch is mostly correct in his answer. You should really escape the string on your own. Something like this should protect against most injections:
@KingCrunch在答案中大多是正确的。你应该自己逃避字符串。这样的事情可以防止大多数注射:
//make sure $table and $column only contain alphanumeric chars
$table = preg_replace("/[^A-Za-z0-9]/", '', $table);
$column = preg_replace("/[^A-Za-z0-9]/", '', $column);
$query = "SELECT FROM `{$table}` WHERE `{$column}` = ?"