创建php fom从表bd

时间:2017-02-04 14:35:51

标签: php mysql

表deportes有2列,共4行:

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

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

带有选择多个选项的表单:

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

从表单中获取值

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

现在这个

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

这种方式将值插入另一个表

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

结果是我在表mec

的字段idD中得到值“0”

1 个答案:

答案 0 :(得分:0)

如果您print_r $_POST['fan'],则会看到数组。要获得数组的每个值,您应该使用forforeach迭代它:

$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
}

当然,你必须转移到准备好的语句,以保护你的代码免受sql注入。这个question会给你一个开始。