Insert multiple rows with CodeIgniter

There will definitely be occasions during the development of an Application where you will need to setup  “many to many” database tables (aka junction tables). For instance, I’m creating a section of an application where you can sign users up for notifications based on their email. For each notification, you need to be able to select as many countries as you wish. Instead of storing all the countries in 1 table cell separated by commas, I went ahead and setup a new table to house this data. This will make working with this data easier down the road, since this application will be expanding.

I’m using CodeIgniter for this example, something you will see me frequently blogging about. Currently, this is my favorite PHP Framework using the my_model / my_controller methodology.

When the form is completed, a new row will be inserted into this table for each country selected. Thus, if 50 countries were selected, it would create 50 rows in the table.

For the sake of this example, I will not be validating or using any models.

First, I’ll need to setup my checkbox in my form:

Insert multiple rows with CodeIgniter

A standard checkbox right? Wrong, it’s very important to include the [ ] after the name on the checkbox to create an array.

Now for the insertion code:



That’s it! If your not using CodeIgniter this should still be useful in normal PHP.