PopeyeDoyle
PopeyeDoyle

Reputation: 13

Insert multiple rows with SQL/PHP

I have an input field where the user can specify a number between 1-22. Now let's say they enter 14. Then I want to insert 14 rows. What the best way to do this? With either SQL or 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.

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.

Upvotes: 0

Views: 110

Answers (2)

Picoss
Picoss

Reputation: 2057

You should use MySQL multiple insert:

$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:

"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)')"

Upvotes: 2

Sterling Archer
Sterling Archer

Reputation: 22435

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
}

Upvotes: 0

Related Questions