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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)