创建php表单从表bd中选择多个值

问题描述:

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>
";
        }
    ?>            
</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

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.