0

The table deportes has 2 columns with 4 rows:

<?php
$sql = 'SELECT * FROM deportes';
$resul = mysqli_query($conexion, $sql);

$deportes = array();    
while ($fila = mysqli_fetch_array($resul))
{
     $deportes[] = $fila;
}       
?>

The form with the select multiple options:

<select name="fan[]" multiple="multiple"> 
    <?php
        foreach ($deportes as $aficion)
        {
            echo "<option value='".$aficion['idD']."'";
            echo " >{$aficion['nombreDep']}  </option>\n";
        }
    ?>            
</select>

Get the values from the form

<?php
if (isset($_POST['fan']))
    {
    $sport = $_POST['fan'];
    }
?>

Now this

<?php $sport = mysqli_real_escape_string($conexion, $sport); ?>

This way insert the values in another table

$idPersona = mysqli_insert_id($conexion);           
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";

And the result is i get the value "0" in the field idD from table mec

mymiracl
  • 583
  • 1
  • 16
  • 24
albno
  • 9
  • 2
  • 2
    `$sport` is an array, not a string. Are you trying to insert `$sport` array data as comma separated values in the table? – Rajdeep Paul Feb 04 '17 at 14:48
  • No. The values for idD in deportes table are 1, 2, 3, 4. I would like to insert in the field idD in mec table these values one by one. – albno Feb 04 '17 at 15:03
  • What's the purpose of this statement `$idPersona = mysqli_insert_id($conexion);` ? Do you have *any other* `INSERT` query apart from this? – Rajdeep Paul Feb 04 '17 at 15:12

1 Answers1

0

If you print_r your $_POST['fan'], you will see that this is array. To get every value of array you should iterate over it, with for or foreach:

$idPersona = mysqli_insert_id($conexion);           
foreach ($_POST['fan'] as $sport) {
    echo $sport;   // you will see that now it is string
    $sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
    // execute your query
}

And of course you must move to prepared statements to protect your code from sql-injection. This question will give you a start.

Community
  • 1
  • 1
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Thank u so much :) – albno Feb 05 '17 at 21:32
  • Hello, again. Now i have other issue, i need to keep the values selected from the form: – albno Feb 08 '17 at 11:32
  • Im trying to use a function like this: ` function verificarListaMultiple($array, $valor) { if (in_array($valor, $array)) { echo 'selected = "selected"'; } } But, there is no way to keep the values. It would be so appreciated some kind of help. Thank you – albno Feb 08 '17 at 11:37
  • Please, create __new__ question with your problem. Comments are not for this. – u_mulder Feb 08 '17 at 11:39