Mysql
 sql >> Database >  >> RDS >> Mysql

PDO MySQL:inserisci più righe in una query

Un modo semplice per evitare le complicazioni sarebbe qualcosa del genere

$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();
}

Tuttavia, questo esegue l'istruzione più volte. Quindi, è meglio se creiamo una query singola lunga per farlo.

Ecco un esempio di come possiamo farlo.

$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