Multiple records deletion in php using my sql

Now a days while developing web applications it is common requirement to delete multiple records same as gmail is offering deletion of multiple records. So lets have a look how to delete multiple records in php using my sql as a database server.

Create view-recs.php file to select and display all records



======(CODE) view-recs.php)======

<html>
<head>
<title>Multiple Deletion in php</title>
<?php
require_once('conn.php');
$sql="select * from $tbl_name";
$result=mysql_query($sql);
?>
</head>
<body>
<table width="600" cellpadding="2" cellspacing="2" style="font-family:Verdana; font-size:12px;">
<tr>
<form name="form1" method="post" action="do-delete.php">
<tr bgcolor="#eaeaea">
<th>Roll No</th>
<th>Name</th>
<th>Father Name</th>
<th> </th>
<th> </th>
</tr>
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row[0]; ?> </td>
<td align="center"><?php echo $row[1]; ?> </td>
<td align="center"><?php echo $row[2]; ?> </td>
<td align="center"> <input type="checkbox" name="del[]" value="<?php echo $row[0]; ?>"> </td>
</tr>
<?php
}
?>
<tr>
<td colspan="3">
<input type="submit" value="Delete">
</td>
</tr>
</form>
</table>
</body>
</html>

This is simple code, you have already learned this code in previous posts, but the most important part of this code is
, this code is responsible for making array for checkboxes that contains value which is unique for every checkbox and coming from database too.

Now we want to develop a php file that will perform multiple deletion process, in this example i use name for this php file is do-delete.php, so lets have a look over the code that how multiple deletion process will occur after selecting multiple check boxes and then clicking on Delete button.

======do-delete.php======


<?php
require_once('conn.php');
if (isset($_POST['del']) && is_array($_POST['del']))
{
foreach ($_POST['del'] as $num => $value)
{
$sql="delete from $tbl_name where rollno='$value'";
$result=mysql_query($sql);
}
}
header("location:view-recs.php");
?>

In this above mentioned code, the most important code snippet is

foreach ($_POST['del'] as $num => $value)
{
$sql="delete from $tbl_name where rollno='$value'";
$result=mysql_query($sql);
}


we apply foreach loop that will go through the array of checkboxes and perform deletion process against selected checkboxes.

====== conn.php======



<?php
$host="localhost";
$user="root";
$db_pass="";
$db_name="tutorials";
$tbl_name="student";
mysql_connect("$host","$user","$db_pass") or die("cannot connect to the database server");
mysql_select_db("$db_name") or die("cannot select the database");
?>

1 comments:

  • Anonymous
     

    Im a beginner in php and this tutorial is just the thing i need however when i follow the instructions upload the files, when i come to delete a record the page just refreshes after i have pressed the delete button and nothing happens? Please advise if possible, would be much appreciated.