Multiple Database Entries from One Form Submission?

Lets say I have a newspaper type database.

I have an article table with the following columns:


Then I have a Article Category Table with the following Columns:


Then I have another table that links to two together with the following columns:


I want a make a form that displays all of the Categories with a select statement that delivers code similar to the following so that I can select which category the News Article can go to:

<input type=“checkbox” name=“option1” value=“(category_id_1)”> News<br>
<input type=“checkbox” name=“option2” value=“(category_id_2)”> Sports<br>
<input type=“checkbox” name=“option2” value=“(category_id_3)”> Weather<br>

For each option checked I want to put a seperate entry in the third table I mentioned.

So lets say that I am adding an article. The article ID ends up being 557 and I select Sports and Weather I want to add two entries with the following data:

Article_ID - Category_ID
557 - 2
557 - 3

What is the best way for me to go about doing this?

Change the name attribute on your checkboxes:

<input type="checkbox" name="option[]" value="(category_id_1)"> News<br>
<input type="checkbox" name="option[]" value="(category_id_2)"> Sports<br>
<input type="checkbox" name="option[]" value="(category_id_3)"> Weather<br> 

Now, when you process the form submission, you can access ‘option’ as an array:

$options = !empty($_POST['option']) ? $_POST['option'] : array();
foreach($option as $opt) {
    // $opt now contains the category_id
    // insert relation into database

The trick here is the name of the checkbox (option). That makes PHP parse it as an array when the form is submitted :slight_smile:

In addition to immerse’s answer, you should create an insert statement that inserts all rows in one go, avoiding multiple database calls.

How would you do that?

INSERT INTO article_categories (article_id,category_id) VALUES
( 557,2 ) , ( 557,3 ) , …

one sql statement, multiple rows inserted