简体   繁体   English

使用SQL / PHP插入多行

[英]Insert multiple rows with SQL/PHP

I have an input field where the user can specify a number between 1-22. 我有一个输入字段,用户可以在1-22之间指定一个数字。 Now let's say they enter 14. Then I want to insert 14 rows. 现在让我们说他们输入14.然后我想插入14行。 What the best way to do this? 最好的方法是什么? With either SQL or PHP. 使用SQL或PHP。

$current_number_of_ranks = 7;
$number_of_ranks = 14;

INSERT INTO ranks (c_id, name) VALUES (67, '(new rank)')

EDIT: Also, lets say theres currently 7 rows with c_id 67 and they enter the number 9. I only wanna insert 2 rows. 编辑:另外,让我们说当前7行与c_id 67并且他们输入数字9.我只想插入2行。

EDIT: This is just an example. 编辑:这只是一个例子。 I got everything working except figuring out how to insert multiple rows. 除了弄清楚如何插入多行之外,我得到了一切。 All I need help with is how to insert multiple rows. 我需要帮助的是如何插入多行。

You should use MySQL multiple insert: 您应该使用MySQL多个插入:

$number_of_ranks = 14;

$value = implode(',', array_fill(0, $number_of_ranks, "(67, '(new rank)')"));
$query = 'INSERT INTO ranks (c_id, name) VALUES ' . $value;
// then execute the query 

the result of $query will be: $query的结果将是:

"INSERT INTO ranks (c_id, name) VALUES (67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)'),(67, '(new rank)')"

With the assumption that you have a good reason for random inserts.. 假设您有充分的理由进行随机插入..

You could place the query into a loop 您可以将查询放入循环中

$number_of_ranks = 14;
for ($i=0; $i<$number_of_ranks; $i++) {
    mysqli_query("INSERT INTO ranks (c_id, name) VALUES (67, '(new rank)')");
    //use normal db class if you have written one of course
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM