简体   繁体   English

使用PDO将大量变量插入表中

[英]Insert large amount of variables into table using PDO

I have a large form with about 25 input fields. 我有一个包含大约25个输入字段的大表单。

Im trying to insert them into my table and the only way i know how is using the following... 我试图将它们插入我的表中,这是我知道如何使用以下内容的唯一方法...

$count = $dbh->exec("INSERT INTO directory(field1, field2) VALUES (':value1', ':value2')");

As I have so many post variables, is there a better way to do this than type each and everyone into my query? 由于我有这么多的帖子变量,有没有比将每个人和每个人都输入我的查询更好的方法呢?

Dynamic prepared queries 动态准备的查询

You can build your query dynamically from $_POST array: 您可以从$ _POST数组动态构建查询:

But, NEVER trust user input, which means you cannot trust that data in $_POST will contain valid column names. 但是,永远不要信任用户输入,这意味着你不能相信$ _POST中的数据将包含有效的列名。

1. Sanitize the post data 1.清理帖子数据

You can define an array of whitelisted column names $whitelist = array('field1', 'field2', ...) , and then use: 您可以定义白名单列名称$whitelist = array('field1', 'field2', ...) ,然后使用:

$data = array_intersect_key($_POST, array_flip($whitelist));

to find the intersection between the whitelisted columns and your $_POST array. 找到列入白名单的列和$ _POST数组之间的交集。 (Thanks @BillKarwin) (谢谢@BillKarwin)

2. Build the query 2.构建查询

private function buildInsertSql($data, $table) {
    $columns = "";  
    $holders = "";  
    foreach ($data as $column => $value) {  
       $columns .= ($columns == "") ? "" : ", ";  
       $columns .= $column;  
       $holders .= ($holders == "") ? "" : ", ";  
       $holders .= ":$column";  
    }  
    $sql = "INSERT INTO $table ($columns) VALUES ($holders)";  
    return $sql; 
}

This will give you a SQL statement of the form: 这将为您提供表单的SQL语句:

$sql = INSERT INTO directory (field1, field2) VALUES (:field1, :field2)

and prepare the statement: 并准备声明:

$stmt = $dbh->prepare($sql);

3. Bind parameters 3.绑定参数

You can then dynamically bind parameters to the placeholders: 然后,您可以将参数动态绑定到占位符:

foreach ($data as $placeholder => $value) {
    $stmt->bindValue(":$placeholder", $value);
 }

and execute it: 并执行它:

$stmt->execute();

A little more advanced... 更先进......

You can build INSERT statements dynamically, but you should be careful about restricting the POST fields. 您可以动态构建INSERT语句,但是应该注意限制POST字段。 Don't trust the request contains only valid columns. 不要相信请求只包含有效列。

Also delimit table and column identifiers. 还分隔表和列标识符。 MySQL uses the back-tick as the identifier delimiter by default. 默认情况下,MySQL使用反向标记作为标识符分隔符。

function execInsert($pdo, $table, $_POST) {
    // get a list of columns in $table, either by hard-coding them per table, 
    // or by querying DESC or INFORMATION_SCHEMA
    $real_columns = array('col1', 'col2', 'col3');

    $fields = array_intersect_key($_POST, array_flip($real_columns));
    if (!$fields) {
        // no POST fields match the real columns
        return false;
    }

    $columns = array_map(function($col) { return "`".$col."`"; }, array_keys($fields));
    $holders = array_map(function($col) { return ":".$col; }, array_keys($fields));
    $values = $fields;

    $sql = "INSERT INTO `$table` (" . join(",", $columns) . 
        " VALUES (" . join(",", $holders) . ")";  

    if (($stmt = $pdo->prepare($sql)) === false) {
        die(print_r($pdo->errorInfo(), true));
    }
    if (($retval = $stmt->execute($values)) === false) {
        die (print_r($stmt->errorInfo(), true));
    }
    return $retval;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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