简体   繁体   中英

multiple submit buttons in a loop php

I need to display a list of elements and after each and every element a delete button is added dynamically. Whenever the user presses a delete button the corresponding element should be deleted and rest of the list should be shown. I have written the following php code to accomplish this:

for($i=0;$i<count($b);$i++)
 { 
   $a=$b[$i];
     echo "<li>$b[$i]</li> ";
   $p="remove"."$j";
   echo "<form  action='' method='post'> <input class='z' type='submit' name='$p'  value='delete'> </form>";
   $j++;

 }
  if($_POST['$p'])
{
   //code for deleting 
}

The problem is whenever the user presses the delete button only the last element added is getting deleted and rest of the buttons are not working.Please tell me how to detect which button has been pressed dynamically and delete the corresponding element using php.

Thank you

You need to associate each button with its respective element. You'll wanna do this dynamically with an id or hidden input or something.

for($i=0;$i<count($b);$i++)
 { 
   $a=$b[$i];
     echo "<li>" . $b[$i] . "</li> ";
   $p="remove" . $i;
   echo "<form  action='' method='post'>";
   echo "<input type='hidden' name='item' value='" . $i . "' />";
   echo "<input class='z' type='submit' name='delete'  value='delete'> </form>";
   $i++;

 }
  if($_POST['delete'])
{
   $item = $_POST['item'];
   //code for deleting $item
}

You're putting each delete button in its own form - you could also add in a hidden input with the ID to remove?

 echo "<form  action='' method='post'>\n";
 echo "<input type='hidden' name='toDelete'  value='" .$i ."'>\n";
 echo "<input class='z' type='submit' name='$p'  value='delete'>\n";
 echo "</form>\n";

You'd then look for the element to delete with:

if(isset($_POST['toDelete'])) {
   // $_POST['toDelete'] has the index number of the element to remove
}

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