Looka
Looka

Reputation: 27

How to insert values of multiple select

I have a list multiple select, this is the code :

<form method="post" action="">
      <select name=thematique[] multiple>
        <option value="1"> MIE </option>
        <option value="2">  Migration </option>
        <option value="3"> Réunification familiale </option>
      </select>
      <button type="submit" class="button" name="categoriser">Catégoriser</button>
    </form>

My problem is if I select MIE + Migration + Réunification familiale, so I have 3 lines in my data base for the same ID. I want to have one line which will insert all options of the select (0 1 2 or 3).

$id_struct=$_POST['id_struct'];
$thematique=$_POST['thematique']);
foreach($thematique as $item) {
                $string= $item.' ';
                echo $string;

    $bdd->exec("INSERT INTO categorisation SET id_thematique=$string
                    WHERE id_struct=$id_struct");
    }

PS : id_thematique is a foreign key.

Upvotes: 3

Views: 5283

Answers (3)

Dedy Chaidir
Dedy Chaidir

Reputation: 927

You can use array of you thematique as object array:

$thematiqueArray = array(0=>'MIE', 1=>'Migration', 2=>'Réunification familiale');

set your html options element like this:

<option value=0>MIE</option>
<option value=1>Migration</option>
<option value=2>Réunification familiale</option>

and on your POST catching similiar like this:

$thematique=$_POST['thematique']);
foreach($thematique as $key => $value) {
            $item = $thematiqueArray[$key];
            echo $item;
}

Upvotes: 1

B.G.
B.G.

Reputation: 6016

One solution would be to give base2 values to your select. Like 1,2,4,8 etc... then you can sum the selected values up, and know which are selected. But this only works if you don't need the values in other places.

Upvotes: 0

Saty
Saty

Reputation: 22532

1) You need to add VALUE attribute in your select box .

2) Don't treated INSERT query AS UPDATE query

Your select box

<select name=thematique[] multiple>
        <option value="MIE"> MIE </option>
        <option value="Migration"> Migration </option>
        <option value="Reunification_familiale"> Reunification familiale </option>
      </select>

Your php file for insert into three separate field

<?php 
foreach ($_POST['thematique'] as $thematique) 
{
 ///your insert code//
 $bdd->exec("INSERT INTO categorisation (`thematique`) VALUES ('".$thematique."'");
}?>

Upvotes: 1

Related Questions