0

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.

3
  • 1
    they are gonna insert 14 rows? of what? random data?, or are you gonna ask the user what does he wants to insert? Commented Jul 5, 2013 at 23:11
  • Then you need to also SELECT prior INSERTING to know how many rows already exist for that given ID. Commented Jul 5, 2013 at 23:30
  • I have already done that. This is just an example. Commented Jul 5, 2013 at 23:35

2 Answers 2

2

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)')"
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

This is not the optimal way to do it. Performing any type of query in a loop is usually frowned upon due to performance reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.