DELETE multiple rows in MySQL with checkboxes
Had many questions about this one, finally coded a
dirty DELETE script, please play as needed, improvements welcome!
Based on:
Update multiple rows in MySQL with checkboxes
PHP Code:
<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE test_mysql SET status = '".(isset($activate)?'Y':'N')."' WHERE id IN $id" ;
$result = mysql_query($sql) or die(mysql_error());
}
// * Delete multiple via checkboxes * START *
if(isset($_POST['delete'])) {
foreach($_POST['delete'] as $value) {
$sql_query = mysql_query("DELETE FROM $tbl_name WHERE id = $value");
}
}
// * Delete multiple via checkboxes * END *
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DELETE multiple rows in mysql with checkbox</title>
</head>
<body>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="frmactive" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1">
<tr>
<td colspan="6"><input name="activate" type="submit" id="activate" value="Activate" />
<input name="deactivate" type="submit" id="deactivate" value="Deactivate" />
<input name="delete" type="submit" id="delete" value="Delete" /></td>
</tr>
<tr>
<td> </td>
<td colspan="5"><strong>Update multiple rows in mysql with checkbox</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Delete</strong></td>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Firstname</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Status</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FF0000" align="center"><input type="checkbox" name="delete[]" id="delete[]" value="<? echo $rows['id']; ?>" /></td>
<td><? echo $rows['id']; ?></td>
<td><? echo $rows['name']; ?></td>
<td><? echo $rows['lastname']; ?></td>
<td><? echo $rows['status']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="6" align="center"> </td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
Enjoy!