Insert multiple rows into database

Sebelumnya kalo mau insert data yang banyak sekaligus pake cara looping data dari hasil foreachnya terus di query-in dah, ehh ternyata cara itu agak “expensive process” hahahaa so beud daha pake istilah inggris segala 😀
Nah kenapa pake istilah inggeris?? jadi postingan ini tuh sebenernya dapet pencerahan dari Sini nih, oke langsung aja kita ke skripnya :

<?php
class Koneksi extends PDO {
    private $dbname     = "insert_multiple";
    private $host       = "localhost";
    private $user       = "postgres";
    private $password   = "password";
    private $port       = 5432;
    
    
    public function __construct() {
        try {
            parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->password");
        } catch(PDOException $e) {
            echo    $e->getMessage();  
        }
    
    }
}

$db = new Koneksi();

echo '<form method="post" action="">';
$i = 0;
for($i; $i < 3; $i++){
      echo '<br><input type="text" name="x[]" value="">FIELD1<br>';
      echo '<br><input type="text" name="z[]" value="">FIELD2<br>';
}
echo '<br><input type="submit" name="simpan">';
echo '</form>';

if($_POST['simpan']){
      // an array items to insert
      $array = $_POST['x'];
      // begin the sql statement
      $sql = "INSERT INTO table1 (field1, field2 ) VALUES ";

      // this is where the magic happens
      $it = new ArrayIterator( $array );

      // a new caching iterator gives us access to hasNext()
      $cit = new CachingIterator( $it );

      // loop over the array
      foreach ( $cit as $value )
      {
	  // add to the query
      //     $sql .= "('".$cit->key()."','" .$cit->current()."')";
	  $sql .= "('".$_POST['x'][$cit->key()]."','" .$_POST['z'][$cit->key()]."')";
	  // if there is another array member, add a comma
	  if( $cit->hasNext() )
	  {
	      $sql .= ",";
	  }
      }

      // echo $sql;
      // insert data
      $db->query($sql);
}
Advertisements
This entry was posted in php. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s