-1

Im using the following php for loop to insert array values in database. I need correction to my code.I want to query out side the for loop.Please help me in correcting my code.

<?php
             /*********************/
             $data = $_REQUEST['columns_one'];
             $store_data = explode(",",$data);
            foreach($store_data as $key =>$value)
            {
            //echo $value;
            $query = "insert into fb_savedforms(form_id,form_structure) values ('','".$value."')";
            $result = mysql_query($query);
            } 
            /**************************************/
        ?>
Sam
  • 27
  • 2
  • 5

3 Answers3

1

Use batch insert to build your query in the loop, but only execute it once.

From How to do a batch insert in MySQL

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Community
  • 1
  • 1
Ayush
  • 41,754
  • 51
  • 164
  • 239
1

Try something like this:

$data = $_REQUEST['columns_one'];
$store_data = explode(",",$data);
//setup the insert query
$query = "INSERT INTO fb_savedforms(form_id,form_structure) VALUES ";
$values = array(); //store all the new rows
foreach($store_data as $key =>$value){
  $values[] = "('','".$value."')";
}
$query .=  implode(',', $values) . ';';
$result = mysql_query($query);

Big Disclaimer: This code has not been tested, but should illustrate that you can have multiple value sets.

Tim Lytle
  • 17,549
  • 10
  • 60
  • 91
-2
$data = $_REQUEST['columns_one'];
             $store_data = explode(",",$data);
            $query = '';
            foreach($store_data as $key =>$value)
            {
            //echo $value;
            $query .= "insert into fb_savedforms(form_id,form_structure) values ('','".$value."'); ";

            } 
$result = mysql_query($query);
  • You're just going to end up with a string of insert statements like this. This is exactly why batch insert exists. – Ayush Nov 01 '12 at 05:54