为什么不能将表名传递给准备好的PDO语句?

$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
    var_dump($stmt->fetchAll());
}

是否有另一种安全的方法将表名插入SQL查询?有了安全,我的意思是我不想做

$sql = "SELECT * FROM $table WHERE 1"

当前回答

在PDO中,表名和列名不能被参数替换。

在这种情况下,您只需要手动过滤和清除数据。一种方法是将简写参数传递给动态执行查询的函数,然后使用switch()语句创建用于表名或列名的有效值白列表。这样用户输入就不会直接进入查询。例如:

function buildQuery( $get_var ) 
{
    switch($get_var)
    {
        case 1:
            $tbl = 'users';
            break;
    }

    $sql = "SELECT * FROM $tbl";
}

通过不保留默认大小写或使用返回错误消息的默认大小写,可以确保只使用您希望使用的值。

其他回答

(回答晚了,请参考我的旁注)。

同样的规则也适用于创建“数据库”。

不能使用预准备语句绑定数据库。

例如:

CREATE DATABASE IF NOT EXISTS :database

不会起作用。使用安全列表代替。

旁注:我添加了这个答案(作为一个社区wiki),因为它经常用于结束问题,有些人在尝试绑定数据库而不是表和/或列时发布了类似的问题。

简短的回答是否定的,你不能在PDO的Prepared execute语句中使用动态表名、字段名等,因为它会向它们添加引号,这会中断查询。但是如果你可以净化它们,那么你就可以安全地把它们放在查询本身中,就像你使用MySQLi一样。

正确的方法是使用mysqli的mysqli_real_escape_string()函数,因为mysql_real_escape_string被匆忙地从PHP中删除,而没有考虑它如何影响动态结构应用程序。

$unsanitized_table_name = "users' OR '1'='1"; //SQL Injection attempt
$sanitized_table_name = sanitize_input($unsanitized_table_name);

$stmt = $dbh->prepare("SELECT * FROM {$unsanitized_table_name} WHERE 1"); //<--- REALLY bad idea
$stmt = $dbh->prepare("SELECT * FROM {$sanitized_table_name} WHERE 1"); //<--- Not ideal but hey, at least you're safe.

//PDO Cant sanitize everything so we limp along with mysqli instead
function sanitize_input($string)
{
   $mysqli = new mysqli("localhost","UsahName","Passerrrd");
   $string = $mysqli->real_escape_string($string);

   return $string;
}

至于这个帖子中的主要问题,其他帖子已经清楚地说明了为什么我们在准备语句时不能将值绑定到列名,所以这里有一个解决方案:

class myPdo{
    private $user   = 'dbuser';
    private $pass   = 'dbpass';
    private $host   = 'dbhost';
    private $db = 'dbname';
    private $pdo;
    private $dbInfo;
    public function __construct($type){
        $this->pdo = new PDO('mysql:host='.$this->host.';dbname='.$this->db.';charset=utf8',$this->user,$this->pass);
        if(isset($type)){
            //when class is called upon, it stores column names and column types from the table of you choice in $this->dbInfo;
            $stmt = "select distinct column_name,column_type from information_schema.columns where table_name='sometable';";
            $stmt = $this->pdo->prepare($stmt);//not really necessary since this stmt doesn't contain any dynamic values;
            $stmt->execute();
            $this->dbInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
    public function pdo_param($col){
        $param_type = PDO::PARAM_STR;
        foreach($this->dbInfo as $k => $arr){
            if($arr['column_name'] == $col){
                if(strstr($arr['column_type'],'int')){
                    $param_type = PDO::PARAM_INT;
                    break;
                }
            }
        }//for testing purposes i only used INT and VARCHAR column types. Adjust to your needs...
        return $param_type;
    }
    public function columnIsAllowed($col){
        $colisAllowed = false;
        foreach($this->dbInfo as $k => $arr){
            if($arr['column_name'] === $col){
                $colisAllowed = true;
                break;
            }
        }
        return $colisAllowed;
    }
    public function q($data){
        //$data is received by post as a JSON object and looks like this
        //{"data":{"column_a":"value","column_b":"value","column_c":"value"},"get":"column_x"}
        $data = json_decode($data,TRUE);
        $continue = true;
        foreach($data['data'] as $column_name => $value){
            if(!$this->columnIsAllowed($column_name)){
                 $continue = false;
                 //means that someone possibly messed with the post and tried to get data from a column that does not exist in the current table, or the column name is a sql injection string and so on...
                 break;
             }
        }
        //since $data['get'] is also a column, check if its allowed as well
        if(isset($data['get']) && !$this->columnIsAllowed($data['get'])){
             $continue = false;
        }
        if(!$continue){
            exit('possible injection attempt');
        }
        //continue with the rest of the func, as you normally would
        $stmt = "SELECT DISTINCT ".$data['get']." from sometable WHERE ";
        foreach($data['data'] as $k => $v){
            $stmt .= $k.' LIKE :'.$k.'_val AND ';
        }
        $stmt = substr($stmt,0,-5)." order by ".$data['get'];
        //$stmt should look like this
        //SELECT DISTINCT column_x from sometable WHERE column_a LIKE :column_a_val AND column_b LIKE :column_b_val AND column_c LIKE :column_c_val order by column_x
        $stmt = $this->pdo->prepare($stmt);
        //obviously now i have to bindValue()
        foreach($data['data'] as $k => $v){
            $stmt->bindValue(':'.$k.'_val','%'.$v.'%',$this->pdo_param($k));
            //setting PDO::PARAM... type based on column_type from $this->dbInfo
        }
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);//or whatever
    }
}
$pdo = new myPdo('anything');//anything so that isset() evaluates to TRUE.
var_dump($pdo->q($some_json_object_as_described_above));

以上只是一个例子,所以不用说,复制->粘贴将不起作用。根据自己的需要进行调整。 现在,这可能不能提供100%的安全性,但是当列名作为动态字符串“进入”时,它允许对列名进行一些控制,并且可以在用户端进行更改。此外,不需要使用表列名和类型构建数组,因为它们是从information_schema中提取的。

使用前者本质上并不比后者更安全,您需要清除输入,无论它是参数数组的一部分还是简单变量的一部分。因此,我不认为对$table使用后一种形式有任何错误,只要您在使用它之前确保$table的内容是安全的(字母加下划线?)。

在PDO中,表名和列名不能被参数替换。

在这种情况下,您只需要手动过滤和清除数据。一种方法是将简写参数传递给动态执行查询的函数,然后使用switch()语句创建用于表名或列名的有效值白列表。这样用户输入就不会直接进入查询。例如:

function buildQuery( $get_var ) 
{
    switch($get_var)
    {
        case 1:
            $tbl = 'users';
            break;
    }

    $sql = "SELECT * FROM $tbl";
}

通过不保留默认大小写或使用返回错误消息的默认大小写,可以确保只使用您希望使用的值。