-1

我使用以下 php for 循环在数据库中插入数组值。我需要更正我的代码。我想在 for 循环之外查询。请帮助我更正我的代码。

<?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);
            } 
            /**************************************/
        ?>
4

3 回答 3

1

使用批量插入在循环中构建您的查询,但只执行一次。

如何在 MySQL 中进行批量插入

使用 VALUES 语法的 INSERT 语句可以插入多行。为此,请包含多个列值列表,每个列表都包含在括号中并用逗号分隔。

例子:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
于 2012-11-01T05:53:42.713 回答
1

尝试这样的事情:

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

大免责声明:此代码未经测试,但应该说明您可以有多个值集。

于 2012-11-01T05:53:49.640 回答
-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);
于 2012-11-01T05:52:40.690 回答