通过变量从foreach循环发送多个值

时间:2015-11-02 14:09:18

标签: php

我有一个foreach循环(见下文):

<form action="code/update-to-dispatched.php" method="post" name="markAsDispatched">
    <?php
        foreach ($orders as $row) {
            $_POST['Username'] = $row['Username'];

            echo "<tr class='even'>";
            echo "<td>";
            echo "<strong>Order Date:</strong> ". $row['OrderDate'] ." <br />";
            echo "</td>";           
            echo "<td>";
            echo "<strong>Order ID:</strong> ". $row['OrderID'] ."";
            echo "</td>";
            echo "<td>";
            echo "<strong>Username:</strong> <input type='text' name='username' value=". $row['Username'] ." readonly style='border: 0; background: none;'>";
            echo "</td>";
            echo "<td>";
            echo '<input type="checkbox" name="chkBox[]" id="chkBox" value="'. $row['OrderID'] .'">';
            echo "</td>";
            echo "</tr>";
        }
    ?>

    <span class="tag"><a href="javascript:checkall('markAsDispatched','chkBox',true)">CHECK ALL</a></span>
    <span class="tag"><a href="javascript:checkall('markAsDispatched','chkBox',false)">UNCHECK ALL</a></span>
    <input type="submit" name="markAsDispatched" value="MARK AS DISPATCHED" />
</form>

我目前在我的数据库中有3个订单,因此上面的代码显示了3个订单。我试图通过$ _POST ['Username']传递来自该字段的所有电子邮件地址。为什么post变量只等于最后一封电子邮件,而不是逗号分隔的列表,如“email1 @ email.com,email2 @email.com,email3 @email.com”?

1 个答案:

答案 0 :(得分:1)

如果您想要以逗号分隔的列表,请尝试以下操作:

$usernames = array();
foreach ($orders as $row) {
            //$_POST['Username'] = $row['Username'];
            $usernames[] = $row['Username'];

            echo "<tr class='even'>";
            echo "<td>";
            echo "<strong>Order Date:</strong> ". $row['OrderDate'] ." <br />";
            echo "</td>";           
            echo "<td>";
            echo "<strong>Order ID:</strong> ". $row['OrderID'] ."";
            echo "</td>";
            echo "<td>";
            echo "<strong>Username:</strong> <input type='text' name='username' value=". $row['Username'] ." readonly style='border: 0; background: none;'>";
            echo "</td>";
            echo "<td>";
            echo '<input type="checkbox" name="chkBox[]" id="chkBox" value="'. $row['OrderID'] .'">';
            echo "</td>";
            echo "</tr>";
        }

echo implode(',', $usernames);

你应该永远不要覆盖$ _POST参数,这是非常糟糕的做法。