1

I've run into this problem twice now, I'll try to be brief:

I want a table where each entry has similar actions. Delete row from table, move row up, move row down. I'm having trouble being able to manipulate the data from any of the keys being pressed in what would appear to be an aesthetically pleasing or even directly functional way.

The problem may be how I'm naming them:

    <tr><td>Example Row 1</td> <td><input name="delete_1" value="delete"></td></tr>
    <tr><td>Example Row 2</td> <td><input name="delete_2" value="delete"></td></tr>
    <tr><td>Example Row 3</td> <td><input name="delete_3" value="delete"></td></tr>
    <tr><td>Example Row 4</td> <td><input name="delete_4" value="delete"></td></tr>

I want my PHP script to see which row I mean to delete when I click on Delete row 4 for example.

I believe it would be incredibly simple to make the value the id of the row and use that to manipulate the data, but then the text changes in the html element.

I've had some bizarre ideas to work around what I see as this problem, using while loops to check if $POST['delete . $incremented_value ] is set, etc but it is horribly overcomplicated.

Apologies if I'm asking a ridiculous question or being blind to the solution, thank you for reading.

1984
  • 297
  • 3
  • 14
  • 1
    You can name the inputs `delete[x]` where `x` is the row. `$_POST['delete']` will then be an array. – tmt Apr 23 '15 at 12:53

1 Answers1

1

change your html to the following

<from method="POST" action"somescript.php">
    <table>
        <tr><td>Example Row 1</td> <td><input type="checkbox" name="delete[]" value="1"></td></tr>
        <tr><td>Example Row 2</td> <td><input type="checkbox" name="delete[]" value="2"></td></tr>
        <tr><td>Example Row 3</td> <td><input type="checkbox" name="delete[]" value="3"></td></tr>
        <tr><td>Example Row 4</td> <td><input type="checkbox" name="delete[]" value="4"></td></tr>
    </table>
    <button type="submit">Delete Checked</button>
</form>

then on the php side

$deletes = array_key_exists('delete', $_POST) ? $_POST['delete'] : [];

foreach($deletes as $delete) {
    // do something
}
Jonathan
  • 2,778
  • 13
  • 23
  • That's very, very interesting. I'd love to learn more about how your method works - can you provide any documentation for it? Also, will this change the text inside my submit buttons to 1, 2, 3, 4? – 1984 Apr 23 '15 at 12:56
  • the way I put it is you do checkboxes, and then one submit button, so you delete them all at once. – Jonathan Apr 23 '15 at 12:58
  • I updated my response to include the full working html. – Jonathan Apr 23 '15 at 13:01
  • @user3621758: It's covered in the [manual](http://php.net/manual/en/faq.html.php#faq.html.arrays). – tmt Apr 23 '15 at 13:02
  • Perfect! I'm not sure how I'm going to manage moving multiple entries above/below each other but once I get that this is great. Thank you very much. – 1984 Apr 23 '15 at 13:11