小编典典

PDO MySQL:在一个查询中插入多行

mysql

您好,我正在制作一个在pdo中进行多次插入的类。

是这样的

INSERT INTO $table (key1,key2,key3,etc) VALUE (value1,value2,value3,etc), (value1,value2,value3,etc), (value1,value2,value3,etc)

搜索后,我发现我必须建立类似

INSERT INTO $table (key1,key2,key3,etc) VALUE (:key1,:key2,:key3,etc), (:key1,:key2,:key3,etc), (:key1,:key2,:key3,etc)

然后用这个执行$this->execute($data); ,其中$data

 0 => 
    array
      'key1' => 'value1'
      'key2' => 'value2'
      'key3' => 'value3'
 1 => 
    array
      'key1' => 'value1'
      'key2' => 'value2'
      'key3' => 'value3'

 etc

问题是我还得到一个错误Array to string conversion$insert->execute($data);如何解决呢?

这是我正在做的一小段。

public function multipleInsert($table, $data = array()) 
{

    # INSERT (name) VALUE (value),(value)
    if (count($data) > 1) 
    {
        $fieldnames = array_keys($data[0]);
        $count_inserts = count(array_values($data));
        $count_values = count(array_values($data[0]));

        # array(????) untill x from first data
        for($i = 0; $i < $count_values; $i++)
        {
            $placeholder[] = '?';
        }

        # array((????),(????),(????)) for query
        for ($i=0; $i < $count_inserts; $i++) 
        { 
            $placeholders[] = '('. implode(',',$placeholder) . ')';
        }

        $query  = 'INSERT INTO '. $table;
        $query .= '(`'. implode('`, `', $fieldnames) .'`)';
        $query .= ' VALUES '. implode(', ', $placeholders);

        $insert = $this->start->prepare($query);

        $i = 1;
        foreach($data as $item) 
        {
            foreach ($item as $key => $value) 
            {
               $insert->bindParam($i++, $item[$key]);
            }
        }

        echo $query;
        $insert->execute();

        $return['status'] = true;
        $return['lastid'] = $this->start->lastInsertId();

        return $return;
    } 
    else 
    {
        die('$data is less then two array, use single insert instead.');
    }
}

阅读 280

收藏
2020-05-17

共1个答案

小编典典

避免并发症的简单方法是这样的

$stmt = $pdo->prepare('INSERT INTO foo VALUES(:a, :b, :c)');
foreach($data as $item)
{
    $stmt->bindValue(':a', $item[0]);
    $stmt->bindValue(':b', $item[1]);
    $stmt->bindValue(':c', $item[2]);
    $stmt->execute();
}

但是,这将多次执行该语句。因此,最好创建一个较长的单个查询来执行此操作。

这是我们如何执行此操作的示例。

$query = "INSERT INTO foo (key1, key2) VALUES "; //Prequery
$qPart = array_fill(0, count($data), "(?, ?)");
$query .=  implode(",",$qPart);
$stmt = $dbh -> prepare($query); 
$i = 1;
foreach($data as $item) { //bind the values one by one
   $stmt->bindValue($i++, $item['key1']);
   $stmt->bindValue($i++, $item['key2']);
}
$stmt -> execute(); //execute
2020-05-17