duanan2732 2018-08-29 17:35
浏览 48
已采纳

一个数组正在获取PHP中的所有输入,我只想要检查行

i want to insert into database several items with its quantity like name of food and its quantity using checkbox that handle the value of the food name.

here is the code:

 <?php      ........
       if(mysqli_num_rows($res) > 0){
        while($row = mysqli_fetch_array($res)){
            echo "<tr>
                    <td><input type='checkbox' value='$row[0]' name='food[]'></td>
                    <td>
                        $row[0]  
                        Qty: <input type='number' value='1' size='1' name='qty[]' id='qty'> 
                    </td>
                    <td align=right>$row[3]</td>
                </tr>";
        }
    }
 ?>

  <input type='submit' value='Add checked' class='btn btnSearch' name='add' id='btnadd'>

 </form>

action:

   <?php
        if(isset($_REQUEST['add']), $_REQUEST['food'])
        {
            $food = $_POST['food'];
            $qty = $_POST['qty'];

            $array = array_combine($food, $qty);

            foreach($array as $f => $q){
                $sql = "insert into entry (foodName,qty, meal_name, date, email) values ('$f', '$q' ,'$meal', '$date', '$email')";
                mysqli_query($cn, $sql);    
            }

            if(mysqli_affected_rows($cn) > 0)
                header("location:fitness.php");
            else
                echo $sql;
        }
   ?>

the problem is .. array $qty is taking all inputs of the table not just the checked.
and im getting the error:

Warning: array_combine(): Both parameters should have an equal number of elements in D:\ABC\First Stage\FitnessAddict\AddFood.php on line 93
  • 写回答

2条回答 默认 最新

  • 「已注销」 2018-08-29 18:22
    关注

    To give you a better answer change this.

     <td><input type='checkbox' value='$row[0]' name='food[]'></td>
    

    to

     <td><input type='hidden' value='$row[0]' name='food2[]'><input type='checkbox' value='$row[0]' name='food[]'></td>
    

    then

    in your code

    foreach($_POST['food2'] as $key=>$val)
    {
        if (in_array($val,$food,true))
            $array[$val] = $qty[$key];
    }
    

    That should work

    So when you check a box in food, it compares the master list in food2 and says here's the matching key you can use for qty.

    The issue is that the checkbox type only passes the checked values, and since you are using an array, you are losing the 'key' to reference qty.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作