Jake
Jake

Reputation: 205

How can I array results from multiple checkbox post values?

I am building a fruit store website.

Currently, I wanna ask to my customers what kind of fruits they love.

So, I created several checkbox options for them.

<form action='customer_favorite' method='POST'>
  <input type='checkbox' name='chk[]' value='banana' />
  <input type='checkbox' name='chk[]' value='mango' />
  <input type='checkbox' name='chk[]' value='apple' />
  <input type='checkbox' name='chk[]' value='orange' />
  <input type='checkbox' name='chk[]' value='kiwi' />
<input type='submit' value='submit' />

and I will put this data into my db like this.

$data = array(
'fav_fruits' = $this->input->post('chk')
);    

$this->db->insert('customer', $data)

The problem is that I can't get result 'apple, orange, kiwi' like this.

Upvotes: 1

Views: 1497

Answers (2)

sandeep
sandeep

Reputation: 2234

You will get result in array with name of your checkbox .In this case you will get like chk[0]=> , chk[1] => , and so on.. in $_POST array.

After that if u have to store it like banana, mango, apple, orange then , do implode of that array using ',' separator..

implode(',' $_POST['chk'])

Upvotes: 1

konsolenfreddy
konsolenfreddy

Reputation: 9671

If you want the clear text values in your DB (not normalized), you can do this:

$data = array(
    'fav_fruits' = json_encode($this->input->post('chk'))
);    
$this->db->insert('customer', $data)

EDIT: changed teh original implode() to json_encode due to @Madmartigan comment

Upvotes: 2

Related Questions