OK i am trying to figure how to use insert_batch
I am tring something like this
function checkboxes($data,$category)
{
$insert=array(
'story'=>$data
'category'=>$category
);
$this->db->insert_batch('stories_to_categories',$insert);
}
For $data i have array, which could have range of values and keys
(
[0] => 1
[1] => 6
[2] => 14
[3] => 15
[4] => 18
)
For category i will have only one value for example 2
I try to achive in my tabele
story category
------------------------
1 2
6 2
14 2
15 2
18 2
Could someone help me i am in such a pain!
You can achieve this by making a little modification to your code. CI documentation shows that batch insert expects an array that is embedded with associative arrays: 1 associative array for each new row to be inserted, mapping the column to the value.
Practically, you would want to build an array like this for your $insert
:
$insert=array(
array('story'=>1, 'category'=>2).
array('story'=>6, 'category'=>2).
array('story'=>14, 'category'=>2).
array('story'=>15, 'category'=>2).
array('story'=>18, 'category'=>2).
);
Since your category is constant, you might want to use a function:
function _insert_($data, $category='2', $options=array('data'=>'story', 'category'=>'category'))
{
$return = array();
foreach ($data as $value)
{
$return[] = array($options['data']=>$value, $options['category']=>$category);
}
return $return;
}
You can then have something like the following:
$this->db->insert_batch('stories_to_categories',_insert_($data));
Hope this helps.
Find Reference(s) below:
See CodeIgniter reference here: CodeIgniter Active Record: #Insert
edit: Codeigniter 3.0 Query Builder Class: inserting data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With