简体   繁体   中英

Active Record equivalent to this MySQL query - CodeIgniter

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? Thank you for any help.

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

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);
    }
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM