Wednesday, June 15, 2016

Delete multiple records

Sometimes we may want to delete multiple records at once for more efficient work. We should provide checkbox for each records and users can select which records to delete.

In this example we should first create a database, a table and insert some data.
Type this sql script:
create database delsampel ;
use delsampel;
create table tabledelete (id int(5) primary key auto_increment, name varchar(50), position varchar(20), level int(2));
insert into tabledelete values(,Janet Jackson,Admin 2,8);
insert into tabledelete values(,Tommy Leo,Admin 1,5);
insert into tabledelete values(,John Connery,Admin 3,4);

then we should create 2 files
1. view.php
2. delete.php

below is the script for both files:
<?php
/*  view.php */
$host = "localhost";
$username = "root";
$password = "";
$database = "delsampel";
$connection = mysql_connect($host, $username, $password);
mysql_select_db($database, $connection) or die("MysQL Error");
$sql = mysql_query("select * from tabledelete");
?>
<html><body>
<form action="delete.php" method="POST">
<?php
echo "<table border=1>";
echo "<tr><th> </th><th>name</th><th>position</th><th>level</th></tr>";
while ($result = mysql_fetch_array($sql))
{
echo "<tr><td><input type=checkbox name=del[] id=del value=$result[id]></td><td>$result[name] </td><td> $result[position] </td><td> $result[level]</td></tr>";
}
?>
</table>
<input type="submit" name="justdel" value="Delete !!" id="justdel">
</form>
</body></html>

delete.php
<?php
/* delete.php */
$host = "localhost";
$username = "root";
$password = "";
$database = "delsampel";
$connection = mysql_connect($host, $username, $password);
mysql_select_db($database, $connection) or die("MysQL Error");
$id = $_POST[del];
$count = count($id); //counting how many rows (from checkbox) to delete
if($_POST[justdel])
{
for ($i=0; $i<$count; $i++)
{
$sql = mysql_query("delete from tabledelete where id=$id[$i]");
}
if ($sql)
{
print "Record successfully deleted<br>";
print "<a href=view.php>Click here to go back</a>";
}
}
?>

those example files can be downloaded here!! 2kb