dongtuanzi1080 2017-02-04 14:35
浏览 43
已采纳

创建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

  • 写回答

1条回答 默认 最新

  • dsvs50005 2017-02-04 15:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化