简体   繁体   中英

Looping through HTML table checked checkboxes using php

i have a similar thread using javascript but i found some problem and some bugs. so i changed to php

so far this is my code

if(!empty($_POST['check'])) {
    foreach($_POST['check'] as $check) {
        //get the html data beside the checked checkboxes

    }
    }else{
        echo '<script language="javascript">';
        echo 'alert("Nothing checked")';
        echo '</script>'; 
    }

and my stripped html code

<tr>
                                <td><?php echo $r['Name'] ?></td>
                                <td><?php echo $r['Age'] ?></td>
                                <td><?php echo $r['Address'] ?></td>

                                <td><input name="check[]" type="checkbox"  ></td>
                            </tr>

i wan't to get the data on the same row where a checkbox is checked. please help me. thanks

You have to loop through the POST data, and assign $r[NAME] = VALUE

For the PHP code:

    array $r;
    foreach($_POST as $post=>$value) {
        //get the html data beside the checked checkboxes
        $r[ $post] = $value;
        } 
    }
    }else{
        echo '<script language="javascript">';
        echo 'alert("Nothing checked")';
        echo '</script>'; 
    }

Assuming that the HTML part your referring to is the result page For the HTML:

<tr>
                                <td><?php echo $r['Name'] ?></td>
                                <td><?php echo $r['Age'] ?></td>
                                <td><?php echo $r['Address'] ?></td>

                            </tr>

First, lets add some data:

<?php

$data = [
  '111' => [
    'Name' => 'John',
    'Age' => '25',
    'Address' => 'Baker street, 11'
  ],
  '222' => [
    'Name' => 'Mary',
    'Age' => '19',
    'Address' => 'Elm street, 14'
  ],
  '333' => [
    'Name' => 'Nick',
    'Age' => '23',
    'Address' => '64th stree, 2'
  ]
];

?>

Output all data items and set checks from previous posted data:

<form method="POST">
<table>
  <?php foreach($data as $id => $item): ?>
  <tr>
    <td><?= $item['Name'] ?></td>
    <td><?= $item['Age'] ?></td>
    <td><?= $item['Address'] ?></td>
    <td><input name="check[]" type="checkbox" value="<?= $id; ?>"
      <?php if (isset($_POST['check']) && in_array($id, $_POST['check'])): ?>
      checked="checked"
      <?php endif; ?>/></td>
  </tr>
  <?php endforeach; ?>
</table>
<input type="submit" />
</form>
<?php if (empty($_POST['check'])): ?>
<script>alert("Nothing checked");</script>
<?php endif; ?>

You'll get reloaded page with properly marked checkboxes after the form submission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM