i am novice in codeigniter. I am trying to insert multiple news that contains some check-box where its values are looped from a database. But i don't know what should code i write for this in controller & Model to insert values. can any one suggest or help me to write code?
view - content.php:
//category name
<?php foreach($result as $aresult) { ?>
<input type="checkbox" name="category_name[]" value="<?php echo $aresult->category_name;?>" /> <?php echo $aresult->category_name;?>
<?php } ?>
controller - news:
public function savecontent()
{
$data=array();
foreach($this->input->post('category_name') as $category_name)
{
$data[] = array('category_name' => $category_name);
}
$data['content_headline']=$this->input->post('content_headline',true);
$this->co_model->save_content($data);
}
Model:
public function save_content($data)
{
$this->db->insert('content',$data);
}
Database structure:
id(auto incr.), category_name(varchar 50), content_headline(varchar 100)
now what should i change to insert multiple row using checkbox ? here there have also another text box/column which also insert in database. but only category name(checkbox value) should be change for all value.
First of all you need to adjust your database structure. Apparently, there's a M:N relation between content
and category
. A more appropriate schema would be:
create table content (
id int not null auto_increment primary key,
content_headline varchar(100) not null
);
create table category (
id int not null auto_increment primary key,
caregory_name varchar(100) not null
);
create table content_category (
content int not null references content,
category int not null references category,
primary key (content,category)
);
Then, you need to adjust your code to reflect the new schema.
Supposing you get $result
from a select * from category
, your view would boil down to:
<label>
Headline:
<input type='text' name='headline'>
</label>
<?php foreach($result as $aresult): ?>
<label>
<input type="checkbox" name="category[<?php echo $aresult->id; ?>]">
<?php echo $aresult->category_name; ?>
</label>
<?php endforeach; ?>
When posted, this will provide you with an array like the following:
array(
'headline'=>'War and Peace',
'category'=>array(
45=>'on',
6=>'on'
)
);
...where 45 and 6 are the checked category ids. Please note that, if no category is checked, the category
array will not be defined.
So the controller becomes:
public function savecontent()
{
$post=$this->input->post();
$selected_cats=(isset($post->category)?array_keys($post->category):array());
$data=array(
'headline'=>$post->headline,
'category'=>$selected_cats
);
$this->co_model->save_content($data);
}
And finally, the model:
public function save_content($data)
{
$this->db->insert('content',array('content_headline',$data['headline']);
$content=$this->db->insert_id(); // what we inserted
foreach($data['category'] as $cat)
$this->db->insert(
'content_category',
array(
'content'=>$content,
'category'=>$cat
)
);
}