user3832367
user3832367

Reputation: 13

How to insert multiple selectbox item in one column

I have a select box which have multiple item select facility

<select multiple="" class="form-control" name="mul[]">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>

                        </select>

Here select box item generate dynamically from another table.so item amount can be increase or decrease.for this reason i cant use set data type.

Now i want to insert selected value in my database table.

MY table look like

id  name   item

1   first   mul[] value

2   second  mul[] value

I want to insert selected item in DB Table column named item.

Also i want to retrieve every row data.

view like

id  name   item

1   first   1,2,3

2   second  2,4

I tried

$select_value=$_POST['mul'];

$sql="insert into mytable (`id`, `name`, `item`) VALUES (null, 'Hallo',$select_value)";

Upvotes: 0

Views: 1227

Answers (3)

Sunny Soni
Sunny Soni

Reputation: 182

'implode' of php is the solution:

echo implode(",",$_POST['mul']);//here $_POST['mul'] = ['1','2','3']

It will output string "1,2,3", insert it your table.

Here is more info about implode implode

Also ,if you want to retrieve records from DB table using your option values then FIND_IN_SET() function of sql will be useful , the query will be :

SELECT * FROM mytable WHERE FIND_IN_SET('option_value',`item`) <>0

Upvotes: 0

oentoro
oentoro

Reputation: 750

This will automatically changes array to string, with comma:

$select_value = join($_POST['mul'],',');

Upvotes: 0

bhushya
bhushya

Reputation: 1317

Use php impload function.

http://www.w3schools.com/php/showphp.asp?filename=demo_func_string_implode

In your case it will b like

$select_value=implode(", ", $_POST['mul']);

$sql="insert into mytable (`id`, `name`, `item`) VALUES (null, 'Hallo',$select_value)";

Then insert it.. :)

Try this.. i hope it helps you

Upvotes: 1

Related Questions