title: PDO Insert foreach
body: <p>I am trying to insert an array of values multiple times into a table.</p>
  
  <p>I have a simple array that is generated by a user checking a box and that's what gets added to the array, I then want to insert each value into a table, I thought I could do it with a foreach loop and iterate $i but it appears I can't, I don't need to worry about security or anything as this is internally used by two people.</p>
  
  <p>here is what I have:</p>
  
  <pre><code>foreach($detailsinvoice as $desc){ 
    $conn3 = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql3 = "INSERT INTO 
               xero_invoices (ContactName, Description)
               VALUES (:ContactName, :Description)";  
    $st3 = $conn3-&gt;prepare ( $sql3 );
    $st3-&gt;bindValue( ":ContactName", $this-&gt;ContactName, PDO::PARAM_STR );
    $st3-&gt;bindValue( ":Description", $desc, PDO::PARAM_STR );
    $st3-&gt;execute();
    $this-&gt;InvoiceNumber = $conn3-&gt;lastInsertId();
    $conn3 = null;
  }
  </code></pre>
  
  <p>This was my first attempt but gathered that the connection can only be used once then exits, so I tried an iteration but again I learnt that you can't do that with the PDO statement.</p>
  
  <pre><code>$i = 3;
  foreach($detailsinvoice as $desc){ 
    $conn[$i] = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql[$i] = "INSERT INTO 
               xero_invoices (ContactName, Description)
               VALUES (:ContactName, :Description)";  
    $st[$i] = $conn[$i]-&gt;prepare ( $sql[$i] );
    $st[$i]-&gt;bindValue( ":ContactName", $this-&gt;ContactName, PDO::PARAM_STR );
    $st[$i]-&gt;bindValue( ":Description", $desc, PDO::PARAM_STR );
    $st[$i]-&gt;execute();
    $this-&gt;InvoiceNumber = $conn[$i]-&gt;lastInsertId();
    $conn[$i] = null;
    $i++;
  }
  </code></pre>
  
  <p><code>detailsinvoice</code> is the array and the ContactName will be the same each time (the Contactname works just need to figure out looping the array)</p>
  
  <p>I would appreciate if someone could point me in the right direction.</p>