-5

我想在一条指令中输入从 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 吗?

4

3 回答 3

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;
于 2013-07-28T16:50:36.137 回答
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
于 2013-07-28T16:50:52.653 回答
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"
于 2013-07-28T17:01:47.600 回答