Skip to content

Best way to Insert multiple rows in a table using PHP/MySQL

Last updated on May 1, 2015

In this tutorial I will show you ,How to insert multiple rows productively into a table with single SQL Query using PHP’s Iterators.

 '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 ); 

?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments