Delete Data from Mysql database using php

Welcome Coders! In this tutorial, we are going to learn how to delete the entries from the Mysql database. We are continuing previous tutorial on data insertion. So please make sure you’ve gone through it before going through this. Get it Here.

We’ll use the connection files as in previous tutorials. Lets create connect.php file and paste the following code in it.

<?php
$servername = "localhost";
$username = "root";
$password = "";

try {
    $conn = new PDO("mysql:host=$servername;dbname=firstdb", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

We’ve discussed previous tutorials of data insert and we are not doing it again. So we are directly jumping to the file delete.php¬†for deleting the records.

<html>
<head>
<title>Delete Data from Mysql database using php</title>
</head>
<body>
<center>
<h1>Delete Data from Mysql database using php</h1>
<form action="delete.php" method="post">
<input type="text" name="id" placeholder="Enter ID" method="post"/>
<input type="submit" name="delbtn" value="Submit" method="post"/></br>
</center>
</form>
</body>
</html>
<?php
include "connect.php";
if(isset($_POST['delbtn'])){
	$del=$_POST['id'];
	try{
		$stmt=$conn->prepare("DELETE FROM users WHERE id=:del");
		
		$stmt->bindparam(":del",$del);
        $result=$stmt->execute();
		if($result===TRUE)
        {
			if(($stmt->rowCount())>0)
			{
				echo "<center>record Deleted successfully!</center>";
			}
			else{
	          echo "<center>No such record exists!</center>";
			}
        }
        else{
	        echo "<center>Something Went Wrong!</center>";
        }
        return true; 
	}
	catch(PDOException $e)
    {
     echo $e->getMessage(); 
     return false;
    }  
  }
?>

We’ve done it. Now lets open main file and enter the id of the record and hit submit. You will see following screens after doing this complete tutorial.

This is view after entering incorrect id.

This is view after Successfully deleting the record.

It’s working fine! Thanks for watching.

Download Source Code

If you have any problems in implementing above tutorial, you can download source code from below link.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.