Php 插入具有匹配数组到表键的关联数组的最有效方法

Php 插入具有匹配数组到表键的关联数组的最有效方法,php,mysql,arrays,pdo,Php,Mysql,Arrays,Pdo,给定以下数组 [0] => array( col1 => val1, col2 => val2, col3 => val3 ), [2] => array( col1 => val1, col2 => val2, col3 => val3 ), [3] => array( col1 => val1, col2 => val2, col3 => val3

给定以下数组

[0] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
),
[2] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
),
[3] => array(
    col1 => val1,
    col2 => val2,
    col3 => val3
)
以及具有相同列名的数据库表
col1
col2
col3

将其插入数据库的最有效方法是什么

我现在有这样的东西

$i = 0;
$db_columns = '';

$column_values = array();

foreach ($rows as $k => $row)
{
    $columns = array();
    $fields = array();

    foreach ($row as $a => $b) 
    {
        $column_values[$a.$i] = $b;
        $columns[] = ':'.$a.$i;
        $fields[] = $a;
    }

    // build up sql values
    $db_columns .= ($db_columns ? ', ' : '').'('.implode(', ', $columns).')';

    $i++;
}

// perform insert
$sql = "INSERT INTO table (".implode(', ', $fields).") 
    VALUES $db_columns";

$query = $db->prepare($sql);
$status = $query->execute($column_values);
它将像这样构建查询字符串

INSERT INTO table (col1, col2, col3)
VALUES (:col10, :col20, :col30), (:col11, :col21, :col31), (:col12, :col22, :col32)
使用数组来匹配绑定变量
:col10
:col20
:col30
:col11


所以一切都很好。它做了我想要的事情,并且工作正常,但是考虑到输入数组键与表匹配,代码对我来说似乎过于复杂。必须有一种更简洁的方法来实现这一点。

您可以通过使用问号参数来简化代码。例如,在以下方面:

$db_columns = '(' .  implode('),(', array_fill(0, count($rows), implode(',', array_fill(0, count($rows[0]), '?')))) . ')';

$sql = "INSERT INTO table (".implode(', ', array_keys($rows[0])).") 
    VALUES $db_columns";

$query = $db->prepare($sql);
$status = $query->execute($column_values);    
$query->execute(array_merge(...array_map('array_values', $rows)));

使用问号参数并发送合并的数组这看起来可能容易受到SQL注入的攻击,或者可能会受到字段内容创建的语法错误的攻击。您没有发布完整的表结构,但是如果要添加到表中的所有列,则无需命名列;意思是删除
(col1,col2,col3)
splash58
,听起来好像它会删除一大块代码。我没想到。我会努力的
ADyson
该数组不是由用户输入生成的。所有数组键都是在代码中的其他地方手动设置的,所以请注意,这些都不应该是问题。@Novocaine