dtye7921 2017-01-13 06:53
浏览 38
已采纳

复选框没有得到正确的顺序

I have these checkboxes used for identifying (if checked) should email the respective client, it's supposed to be pre-checked.

But when it is pre-checked, and then when I unchecked one checkbox e.g multipayment_email[1], when submitted to PHP the one getting unset is the last index multipayment_email[4].

list_payments.php:

<form method="POST">
<?php while($row = mysqli_fetch_array($selectQuery) { ?> 
    <input type="text" name="multipayment_name[]" required/>
    <input type="checkbox" name="multipayment_email[]" checked />
<?php } ?>
</form>

SUBMIT_payment.php:

$names = $_POST['multipayment_name'];
$emails = $_POST['multipayment_email'];

foreach ($names as $key => $name)
{
     $email = isset($emails[$key]) ? 1:0;

     $query = "INSERT INTO payments() VALUES (NULL, '$name', $email)";

     $response['message'] .= $query."<br/>";
}

die(json_encode($response));

So when I submit the form this is the output (given that I unchecked the 2nd index out of 5 check boxes):

"INSERT INTO payments() VALUES (NULL, '1 waw', 1)"

"INSERT INTO payments() VALUES (NULL, '2 wew', 1)"

"INSERT INTO payments() VALUES (NULL, '3 wiw', 1)"

"INSERT INTO payments() VALUES (NULL, '4 wow', 1)"

"INSERT INTO payments() VALUES (NULL, '5 wuw', 0)"

It should be

"INSERT INTO payments() VALUES (NULL, '2 wew', 0)"

any enlightenment?

  • 写回答

3条回答 默认 最新

  • donglian3061 2017-01-13 07:11
    关注

    Try this:

    <form method="POST">
    <?php $idx = 0; ?>
    <?php while($row = mysqli_fetch_array($selectQuery)): ?>
        <input type="text" name="rows[<?php echo $i; ?>][name]" required/>
        <input type="checkbox" name="rows[<?php echo $i; ?>][email]" checked />
        <?php ++$idx; ?>
    <?php endwhile; ?>
    </form>
    

    And so if third checkbox is unchecked, you will obtain the $_POST data in this format:

    array(
        'rows' => array(
            array(
                'name' => 'the value of name 1',
                'email' => 'on'
            ),
            array(
                'name' => 'the value of name 2',
                'email' => 'on'
            ),
            array(
                'name' => 'the value of name 3'
            )
        )
    )
    

    Checkboxes that doesn't check will have the field unset and not being posted, and from there you can easily do an isset check to know if it's checked or not.

    $rows = $_POST['rows'];
    foreach ($rows as $row) {
        $email = isset($row['email') ? 1 : 0;
        $name = $row['name'];
        $query = "INSERT INTO payments() VALUES (NULL, '$name', $email)";
        $response['message'] .= $query."<br/>";
    }
    

    But DO WARNED that this code is susceptible to sql injection. Since this is out of the scope of this question let us not dive into that here :)

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

报告相同问题?