php pdo multi array insert

后端 未结 2 1943
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 19:04

I\'ve been playing around for few hours and trying to sort this out but looks like a hard nut to crack.

I\'m able to do a single array insertion

$pe         


        
相关标签:
2条回答
  • 2021-01-19 19:14

    You cannot do that automatically. Instead you have to iterate it manually and execute each record:

    for ($person as $row) {
        $sth->execute($row);
    }
    
    0 讨论(0)
  • 2021-01-19 19:34

    To take advantage of the insert speed of multiple inserts in MySQL ( http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html ), you can use a prepared statement that builds the larger query. This does add complexity over an more iterative approach, so is probably only worth it for high-demand systems or largish data sets.

    If you have your data as you proposed above:

    $person = array(array('name'=>'Dan', 'age'=>'30'), array('name' =>
    'John', 'age' => '25'), array('name' => 'Wendy', 'age' => '32'));
    

    We're looking to generate a query that looks something like this:

    insert into table (name, age) values (?,?), (?,?), (?,?);
    

    To pull this together you'll want something not totally unlike this:

    $pdo->beginTransaction() // also helps speed up your inserts
    $insert_values = array();
    foreach($person as $p){
       $question_marks[] = '(?,?)';
       $insert_values = array_merge($insert_values, array_values($p));
    }
    
    $sql = "INSERT INTO table_name (name, age) VALUES " . implode(',', $question_marks);
    
    $stmt = $pdo->prepare ($sql);
    try {
        $stmt->execute($insert_values);
    } catch (PDOException $e){
        // Do something smart about it...
    }
    $pdo->commit();
    
    0 讨论(0)
提交回复
热议问题