Php - imap_delete - delete only selected email address

I have a script that prints all inboxes received from the imap server. I added a submit submit button that when clicked should only delete the email that belongs to the button. However, the script is right now deleting all emails when any delete button is clicked. Below is the simplified code:

<?php    
foreach($emails as $email_number) {
?>
 <form method="post">
        <th class="tg-031e"><input type="submit" name="delete_inbox" value="Delete"></th>
        </form>

<?php
if(isset($_POST['delete_inbox'])){
$check = imap_mailboxmsginfo($imap);
echo "Messages before delete: " . $email_number . "<br />\n";
imap_delete($imap, $email_number);
$check = imap_mailboxmsginfo($imap);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($imap);
$check = imap_mailboxmsginfo($imap);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
}
}?>

      

Any ideas on how I can simply delete the email address by clicking the delete button? Also why do I need to refresh the page twice to see the changes after deletion?

+3


source to share


1 answer


There doesn't seem to be any connection between the delete form for the email and the email itself. PHP has no way of knowing exactly which email address you want to remove.

As suggested earlier, one idea is to put the email id in the value of the submit button next to each email.

Then you can grab this from the post data of the delete_inbox input.



 <?php
    if(isset($_POST['delete_inbox'])){
    // Retrieve email i.d value from delete_inbox button
    $email_to_delete = $_POST['delete_inbox'];
    $check = imap_mailboxmsginfo($imap);


echo "Messages before delete: " . $email_number . "<br />\n";
// Delete selected email
imap_delete($imap, $email_to_delete);
$check = imap_mailboxmsginfo($imap);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($imap);
$check = imap_mailboxmsginfo($imap);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
}

foreach($emails as $email_number) {
?>
 <form method="post">
        <th class="tg-031e"><button type="submit" name="delete_inbox" value="<?php echo $email_number; ?>">Delete</button></th>
        </form>

<?php }?>

      

Note. I also removed the $ _POST section of the code from the foreach loop. I see no reason for him to be there.

0


source







All Articles