versatile insertion method for PDO class

走远了吗. 提交于 2019-12-12 01:48:28

问题


this is my insertion method in PDO, it is working 100%. this 'insert' method accepts table, column and value but i want to make it versatile. (i want to insert values with or without the column names)

public function insert($table, $pair = array()){
    try{
        $Sql = "INSERT INTO $table ( ";
        $Sql .= implode(", ", array_keys($pair));
        $Sql .= " )";
        $Sql .= " VALUES (";
        $Sql .= implode(", ", array_fill("0", count($pair), " ?"));
        $Sql .= " )";
        $array = array_combine(array_keys(array_fill("1", count($pair), ":")), $pair);
        $ready = $this->conn->prepare($Sql);
        foreach($array as $key => $value)
        {
            $ready->bindValue($key, $value, PDO::PARAM_STR);
        }
        $ready->execute();
    }
    catch(Exception $e){
        $this->trace .= " • ". $e->getMessage();  
    }
}


$new = new community();
echo $new->insert("table", array("Col1" => "value1", "col1" => "value1"));

回答1:


There are two problems with your function.

  1. It is vulnerable to SQL injection.
  2. It is not flexible. Following the pattern, you are going to have a thousand functions of this kind, which will make your code into mess. Yet it would be always limited subset against real SQL.

What you really need is a function that can create a SET statement out of array and a list of allowed fields.
As a further improvement you may devise a custom placeholder for this statement.

Having these two things you can work out a single general purpose function to run all the DML queries like this:

$db->query("INSERT INTO t SET %u", array("Col1" => "value1", "col1" => "value1"));

It will cost you 3 additional words (insert, into and set), but it will be

  • readable. Everyone can understand SQL. While to read your function one need a documentation
  • flexible. It can support any queries and modifiers, not only one single-formed insert.

Every query you wish you can run with this single function:

$data = array("Col1" => "value1", "col1" => "value1");
$db->query("INSERT IGNORE INTO t SET %u", $data);
$db->query("REPLACE INTO t SET %u", $data);
$db->query("DELETE FROM t WHERE id = ?", $id);
// and so on

No dedicated functions actually needed.

Also, you have to always verify a set of fields against a hardcoded white list, to let a user insert only fields they are allowed to. Do not let a user to alter privileges, messages count and so on.

But even without custom placeholder it would require no set of SQL-mapped functions but just a function to create a SET and a general purpose query execution function:

$allowed = array("name","surname","email"); // allowed fields
$sql = "INSERT INTO users SET ".pdoSet($fields,$values);
$stm = $dbh->query($sql ,$values);


来源:https://stackoverflow.com/questions/17694816/versatile-insertion-method-for-pdo-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!