多个post数组循环不起作用

时间:2016-11-25 22:49:03

标签: php sql arrays mysqli

<?php
    $sql = "SELECT * FROM product ORDER BY product_id DESC";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {

            echo "" . $row["product"] . "\n\n<input type='checkbox' name='product[]' value=" .$row["product"] . ">\n         
     Quantity\n\n<select name='quantity[]'>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
    </select><br />";
        }

    ?>
    <button name="submit" type="submit">submit</button><br />

    <?php

        if (isset($_POST['submit'])) {
            if (is_array($_POST['product'])) {
                foreach ($_POST['product'] as $key => $product_name) {
                    $quantity = $_POST['quantity'][$key];
                    echo $product_name . "\n";
                    echo $quantity . "<br>";

                }
            }
        }
    }

    ?>

我想选择多个产品和数量,但它没有给出我选择的数量值。

example picture1
在示例picture1上你可以看到我选择了2个产品

  • 华硕2
  • Acer 3

但如果点击提交,我会得到像结果一样的结果 example picture2

  • 华硕1
  • Acer 1

1 个答案:

答案 0 :(得分:1)

尝试使用产品ID将复选框链接到选择框。

$sql = "SELECT * FROM product ORDER BY product_id DESC";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {

            echo "" . $row["product"] . "\n\n<input type='checkbox' name='product[".$row['product_id']."]' value=" .$row["product"] . ">\n         
     Quantity\n\n<select name='quantity[".$row['product_id']."]'>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
    </select><br />";
        }