如何使用PHP保持多选表单中的选定值?

时间:2017-02-08 11:51:08

标签: php mysql

我对此表单有疑问。我需要保持选择的价值,我找不到方法。我第一次发布的帖子:Create php fom select multiple taking values from a table bd

表格:

<select name="fan[]" multiple="multiple"> <!-- Aquí se llama a la función verificarListaMultiple -->
    <?php
        foreach ($deportes as $aficion) {
            echo "<option value='".$aficion['idD']."'";
            if (isset($fan)) {
                verificarListaMultiple($aficion,$fan);
            }
            echo " >{$aficion['nombreDep']}</option>\n";
        }
    ?>            
</select>

我尝试使用的功能:

function verificarListaMultiple($array, $valor) {
    if (in_array($valor, $array)) {
        echo 'selected = "selected"';
    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

好的,我这样解决了:

表格插入数据

<?php
    foreach ($deportes as $deporte)                         
        {
        echo "<option value='".$deporte['idD']."'";
        if (isset($depo)) verificarListaMultiple($depo, $deporte['idD']);
                            echo " >{$deporte['nombreDep']}</option>\n";
        }
?>  

然后,将值插入表bd:

<?php
if (isset($_POST['fan']))
    {
        $idPersona = mysqli_insert_id($conexion); 
        foreach ($depo as $sport) {
            $sport = mysqli_real_escape_string($conexion, $sport);
            $sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
            $resul = mysqli_query($conexion, $sql);
}

最后我想编辑edit_Data表单。显示的值必须是以edit_Data格式插入的值,并且必须保持选中状态:

表格编辑 - 数据:

<?php
foreach ($deportes as $deporte)                           
    {
    echo "<option value='".$deporte['idD']."'";
    if (isset($depo)) verificarListaMultiple($depo, $deporte['idD']);
                        echo " >{$deporte['nombreDep']}</option>\n";
    }
?>