简体   繁体   中英

How to extract specific id number from a array of buttons in php?

When I run the code below, it generates a table of columns ID, Product, Price and a column with buttons "edit" and another with "delete". When I debug this program via var_dump(), I get a output of eg: array(1) { [30]=> string(6) "Delete" } or array(1) { [27]=> string(6) "Delete" } with the number in the [] corresponding the the products ID. For the edit column, instead of "Delete" it says "Edit". My Question is, how do I extract the information outputs button 17(corresponding with ID number) of button "Edit" has been clicked?

echo "<form action='' method='POST'>";
        echo "<table border='0' cellpadding='10'>";
        echo "<tr> <th>ID</th> <th>Product</th> <th>Price ($)</th> <th>Edit Menu</th> <th>Delete Menu</th> </tr>";

        // loop through results of database query, displaying them in the table
        while($row = mysql_fetch_array( $result )) {
          echo "<tr>";     // echo out the contents of each row into a table
          echo '<td>' . $row['id'] . '</td>';
          echo '<td>' . $row['name'] . '</td>';
          echo '<td>' . $row['price'] . '</td>';
          echo '<td><input type="submit" value="Edit" name="id1['.$row['id'].']" />' . '</td>';
          echo '<td><input type="submit" value="Delete" name="id2['.$row['id'].']" />' . '</td>';
          echo "</tr>";
          }
          // close table>
          echo "</table>";
          echo '</form>';

          if(isset($_POST['id1'])) {
            var_dump($_POST['id1']);
          }

          if(isset($_POST['id2'])) {
            var_dump($_POST['id2']);
          }

This is what you want.

First you name button like what you need eg. update, delete etc..
Then you can handle it with POST name .
Last you can get your ID by Key from array.

   <?php
    // id list or your source
    $array = [1,2,3];

    // handle edit button with id
    if(isset($_POST['btnEdit'])) {
        var_dump('--- edit');
        var_dump(key($_POST['btnEdit'])); die;
    }

    // handle delete button with id    
    if(isset($_POST['btnDelete'])) {
        var_dump('--- delete');
        var_dump(key($_POST['btnDelete'])); die;
    }
    ?>

and your HTML table:

<?php foreach($array as $id) { ?>

<form method="post" action="">
    <?php echo $id; ?> |
    <input type=submit name="btnEdit[<?php echo $id; ?>]" value="edit">
    <input type=submit name="btnDelete[<?php echo $id; ?>] "value="delete">
</form>

<?php } ?>

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