0

I just wanted some help figuring out how I would insert data that was coming out of a multiple select box, being put into a variable and then into a database.

My database table is structured like this - Table: prd_attr

ID | Product_ID | name | value
-------------------------------
1  | 3          | size | large
2  | 3          | size | medium

So say I have a multiple select box with the name sizes[], and the admin selects 2 sizes for a product to enter into the database. I can get these values in the controller and put them into a variable:

$sizes = $_GET['sizes'];

and pass that variable to the model. Once its there, I can insert the data as a MySQL query like this:

foreach ($sizes as $s)
{
    $query = mysql_query("insert into prd_attr ('name', 'value') VALUES ('size','$s')");
}

But I've learned that mysql_* is deprecated, and since I'm using a framework which provides Active Records I'd like to make use of that. I know the basics of Active Record, but since this is a foreach loop over a variable which can hold any number of values, I don't know how to include a foreach statement with Active Records.

Could someone please explain?

1

2 Answers 2

2

You can also use batch insert in codeigniter:

Try this:

function insert_sizes()
{
    $sizes  =   $this->input->get('sizes');
    foreach ($sizes as $s)
    {
        $data[] = array(
          'name' => 'size',
          'value' => $s
        );
    }
    $this->db->insert_batch('prd_attr',$data);
}

For more details:
http://ellislab.com/codeigniter/user-guide/database/active_record.html

Sign up to request clarification or add additional context in comments.

1 Comment

I was looking at insert_batch! but was confused as the documentation showed that it was an array with arrays inside. I need to learn to take a hint! Thanks
1

You can use this in Model of Codeigniter. Here is a method

function insert_sizes()
{
    $sizes  =   $this->input->get('sizes');
    $data['name']   =   'size';
    foreach ($sizes as $s)
    {
        $data['value']  =   $s;
        $this->db->insert('prd_attr',$data);
    }
}   

4 Comments

Is $data['size'] corresponding to the column name in my database? In that case would it need to be $data['name'] = 'size'; ?
Yes you are right. Sorry i mistyped it should be $data['name'] = 'size';
Thank you, also just wondering does it conform to MVC that you are receiving the input from the view directly in the model? I was told views and models can't directly interact
yes i am doing same if it is not working for you than get it in Controller and pass to model method

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.