listbox items to database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
anshuverma1989
Forum Newbie
Posts: 13
Joined: Sat Jan 10, 2009 2:21 pm

listbox items to database

Post by anshuverma1989 »

Hey people..

I have this hobby listbox with up to near about 15 items where a user can select multiple item.
How can i insert all the items selected in the listbox?

Example Hobbies: If multiple hobbies are selected in the listbox and on press button how should i insert into database?

I saw this tutorial on the website.. in which .. if one item is select it will save one item only and if multiple item is selected, it puts "," between the items selected and then save into database.
but i cannot find it rite now.. so please help me .. how can i do it??
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: listbox items to database

Post by sparrrow »

First, make sure the select form element name is arrayed[].

Code: Select all

<select name="hobbies[]" multiple>
Then iterate through the array in your processing section and build a string with all selected values.

Code: Select all

$hobbies_csv = ""; //instantiate blank string
foreach ($_POST['hobbies'] as $value) {
  if ($hobbies_csv == "") { //If 1st value, no comma
    $hobbies_csv .=  $value;
  } else { //Not first value, so put in comma separator
    $hobbies_csv .=  ",".$value;
  }
}
anshuverma1989
Forum Newbie
Posts: 13
Joined: Sat Jan 10, 2009 2:21 pm

Re: listbox items to database

Post by anshuverma1989 »

thanks for the help. Thanks a ton.

It worked :D
Post Reply