How to delete data from database in PHP using button

In this tutorial we will learn how to delete data from database in PHP using button. I will take a simple blog posts example to demonstrate you delete functionality. Before jumping into the code let’s see how this process will work.

Steps: Delete Data from Database

  • Prompt user to a dialog box when user click on delete button. If he/she wants to continue or not
  • If user select No, Close the dialog box without any action
  • If user select Yes, Get the current record id and delete the respective record
  • Once record will delete. Show success message to user.

For dialog box I will use javascript confirm() function.

php delete data from database using button

Create MySQL Database:

MySQL Database Table:

Database Connection:

Fetch All Data:

Display All Data:

In the above code I use onclick event and pass deletePost javascript function that takes post id as parameter.

Javascript Confirmation:

deletePost is a custom javascript function which trigger confirm dialog box with ‘Are you Sure?’ message. When user will click on ‘OK’ then this function will redirect user to same page but with action and id as query string.

Delete Record:

Above code will check action and id parameter. And delete the record using id. After successfull deletion above code will redirect user to index.php with success query string

Success Message:

All Together:

 

Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *