In this tutorial I will show you ,How to insert multiple rows productively into a table with single SQL Query using PHP’s Iterators.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php // prepare array $array = array( array('name' => 'this is test post 1','description' => 'this is test post description 1'), array('name' => 'this is test post 1','description' => 'this is test post description 1'), array('name' => 'this is test post 1','description' => 'this is test post description 1'), array('name' => 'this is test post 1','description' => 'this is test post description 1'), ); // begin the sql statement $sql = "INSERT INTO test_table (name, description ) VALUES "; $total = count($array); // this is where the magic happens $it = new ArrayIterator( $array ); // Iterate over the values in the ArrayObject: while($it->valid()){ $currentItem = $it->current(); $sql .='('.$currentItem['name'].','.$currentItem['description'].')'; $it->next(); $sql .= $it->key() ? ',' : ';'; } // now we can use a single database connection and query $conn = mysql_connect('db_host','db_user', 'db_password' ); mysql_select_db( 'test_db', $conn ); mysql_query( $sql, $conn ); ?> |