DELETE records from database using MySQLi in PHP:
In this tutorial I will help you to delete records from database using MySQLi in PHP. If you study in PHP so that you know the DELETE statement is used in PHP to remove user all records from database table.
There is easy and simple system I will show you and give more different process of DELETE statement in PHP. In PHP a DELETE statement worked a specific instruction, which is you delete a record from database table using a clause or condition. The WHERE clause is specific to delete record and when you exclude the WHERE clause then all records will be deleted from your database table.
Here click a button and value is pass in the delete.php page, which value you have to set in delete button onclick event. That’s like id value is put in the onclick function name and pass the value other location using JavaScript:
Follow the Example and Source Code:
Table Button:
<button type="button" onclick="delete_records(<?php echo $row['id'];?>)">Delete</button>
pass ID value in the delete page using JavaScript:
<script type="text/javascript"> function delete_records(id) { window.location.href="delete_record.php?id="+id; } </script>
Delete Query:
<?php require_once("dbconnect.php"); $id=$_GET["id"]; $qry=mysqli_query($con,"DELETE FROM `Table Name` where `id`='$id'"); ?>
Set confirm message before Delete record:
<script type="text/javascript"> function delete_records(id) { $Dcon=confirm("Are You Want To Delete It?"); if($Dcon) window.location.href="delete_record.php?id="+id; } </script>
Display success and error message when delete is done:
set success and error message using session variable, while delete records is done or not done. you need to start session when you work with session use session_start() in your page, which page you write delete query code.
<?php require_once("dbconnect.php"); $id=$_GET["id"]; $qry=mysqli_query($con,"DELETE FROM `Table Name` where `id`='$id'"); if($qry){ $_SESSION['success']="Delete Successfully"; header("location:view_page.php"); }else{ $_SESSION['error']="Delete Failed"; header("location:view_page.php"); } ?>
Display message in the redirect page:
You need to use session_start() here.
<?php if(isset($_SESSION['success'])){ echo $_SESSION['success']; } unset($_SESSION['success']); if(isset($_SESSION['error'])){ echo $_SESSION['error']; } unset($_SESSION['error']); ?>