phpmyadmin中使用for循环的多行条目

时间:2013-07-28 16:44:36

标签: php

我想在一条指令中输入从for循环生成的100行。 我正在使用下面但它不起作用。

for($i=$roll_number_start; $i<=$roll_number_end; $i++)
                {
                    $roll_number = $roll_number_format.$i;
                    $p_username = generatePassword();
                    $p_password = generatePassword();
                    $roll_array[] = " ('".$roll_number."',"."'".$student_class."',"."'".$class_section."',"."'".$batch_year."',"."'".$p_username."',"."'".$p_password."')";

                }

                $insert_sql = "INSERT INTO student (roll_number, student_class, class_section, batch_year, p_username, p_password) VALUES".$roll_array;

你可以建议我如何使用一条指令在mysql中插入。

3 个答案:

答案 0 :(得分:0)

修改$roll_array[]并将其设为字符串,如下所示:

$roll_string = '';
for($i=$roll_number_start; $i<=$roll_number_end; $i++)
{
  $roll_number = $roll_number_format.$i;
  $p_username = generatePassword();
  $p_password = generatePassword();
  $roll_string .= "('".$roll_number."',"."'".$student_class."',"."'".$class_section."',"."'".$batch_year."',"."'".$p_username."',"."'".$p_password."'),"
}
$roll_string = substr($roll_string, 0, -1);
$insert_sql = "INSERT INTO student (roll_number, student_class, class_section, batch_year, p_username, p_password) VALUES ".$roll_string;

答案 1 :(得分:0)

有两种方法:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3); -- use 100 times 

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9).....; -- 100 () here

答案 2 :(得分:0)

假设您的数组包含用于插入数据库的格式良好的值集,您只需将数组中的每个项连接成一个字符串即可。 implode执行此操作:

$roll_string = implode( ',',$roll_array );

所以,如果包含$roll_array

[
    "('a','b','c')"
   ,"('d','e','f')"
   ,"('h','i','j')"
]

然后$roll_string现在包含

 "('a','b','c'),('d','e','f'),('h','i','j')"

你可以附加到这样的查询

$SQL = "INSERT INTO table_name( col1,col2,col3 )
VALUES $roll_string"