Forum Moderators: coopster
This is my first post on this forum. :)
I`ve been learning PHP for a couple of months now and I`ve run into this problem.
I have a list of e-mail addresses that each have a checkbox beside it. I want to be able to delete the address for any box that is checked. Now it works for one box, but if I check say two checkboxes, the last e-mail address that was added to the database gets deleted, but not the other one.
I am using:
<input type="checkbox" name="checkmail[]" value="$checkMail">
to delete the entries I`m using the following:
if ($checkmail)
{
$querydeleteemail = "DELETE FROM list WHERE post_email = '$checkmail'";
$resultdelete = mysql_query($querydeleteemail);
emailDelete();
exit;
}
I assume I need a foreach loop? Can anyone tell me exactly how to write a for each loop, because I seem to be having some problems.
Thank you for the help!
This should do you:
for ( $i = 0, $i < count( [php.net]$checkmail), $i++ ){
$query = "DELETE FROM list WHERE post_email = '$checkmail[i]'";
mysql_query( [php.net]$query);
}
mysql_query [php.net](
sprintf [php.net](
"DELETE [mysql.com] FROM table
WHERE field IN [mysql.com] (%s)",
implode [php.net](',', $checkmail)));
will do the same more efficiently.
Andreas
Anyway, I went with Birdmans syntax and it works like a charm. Just one thing, in the $query = "DELETE FROM list WHERE post_email = '$checkmail[i]'"; line the $checkmail[i] should actually be $checkmail[$i] for it to work though!
Cool!
:)
you could use a combination so you only have one query.
$which = 0;
foreach ($checkmail as $mail) {
if ($which!=0) $maillist .= ",";
$maillist .= "'" . $mail . "'";
$which++;
}
$delq = "DELETE FROM list WHERE post_email in (" . $maillist . ")";
mysql_query($delq);
Yes. Thatīs the idea: let MySQL [mysql.com] handle as much as it can. The $checkmail array will only contain the value [w3.org]s of those checkboxes that were actually checked. So there is no need to loop over all those elements and do separate queries.
Neither is there a need to use a loop to build the string to be used in the IN [mysql.com] operator. In my example above implode [php.net] will build the string containing the checked values which is included into the SQL query string by sprintf [php.net].
Andreas
mysql_query [php.net](
sprintf [php.net](
"DELETE [mysql.com] FROM table WHERE field IN [mysql.com] ('%s')",
implode [php.net]("','", $checkmail)));
Andreas