1

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' />
  • I don't know how many checkboxes they will check.

  • When it posts to my server, I want to get the result like this.

    apple, orange, kiwi
    
  • second customer would choose four of them.

    banana, mango, apple, orange
    

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.

  • we don't know how many checkbox values will be there.
  • I want to array values like this 'apple, orange, kiwi'

2 Answers 2

2

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

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

2 Comments

Addition: How do you expect the database to know how to seperate the array in words seperated by comma. (array => apple, banana, mango)? imploding it first will domathat for you.
Other possibly better options include json_encode() and serialize(). If the values have commas in them, they'll be ambiguous with implode(', ', $fruits)
1

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'])

Comments

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.