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.

$servername = "localhost";
$username = "root";
$password = "";

try {
    $conn = new PDO("mysql:host=$servername;dbname=firstdb", $username, $password);
    // set the PDO error mode to 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.

<title>Delete Data from Mysql database using php</title>
<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>
include "connect.php";
		$stmt=$conn->prepare("DELETE FROM users WHERE id=:del");
				echo "<center>record Deleted successfully!</center>";
	          echo "<center>No such record exists!</center>";
	        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.