Delete an entry in SQL using PHP

by | Jun 22, 2021 | PHP

Home » PHP » Delete an entry in SQL using PHP

Introduction

Whatever we see on our website, it is either saved within HTML or being fetched from a table. The HTML has a script file attached with it which calls backend, where SQL codes are written. These SQL codes interact with database. In this article we will learn how to delete an entry in SQL using PHP.

Syntax

DELETE FROM <table name> WHERE <field 1>= '{<local varialble 1>}' and <field 2>= '{<local varialble 2>}'

How to delete an entry in SQL using PHP

In PHP, we need to follow given mandatory steps before we start with any SQL operation:

  1. Define database details
    We need to initialize a database connection and for that we will need its detail. The prerequisite for this will include setup of a database in myphpadmin (if we are using local server). There we will have to create a database and tables.
    In case you have done setup of database and tables in local server: https://localhost/phpmyadmin/

Then, following will be the database details written in PHP

$servername = "localhost";
$username = "root";
$dbname = "<your_database_name>";

 

  1. Create connection
    Once the required connection details are mentioned, we will try to create a connection to database using below query:

    $conn = new mysqli($servername, $username,"", $dbname);
  2. Check connection
    Now the connection setup is done, we need to perform a check to confirm the same using below query:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
  1. Perform Query
    This is the part where we write SQL query to delete data in PHP. In the below query, firstly we get the data coming from frontend in a local variable $obj, and then separate each of the fields according to the column in table. Once we have all the data, then we create a SQL query in a local variable $sql, and pass the same in a function mysqli_query as arguments with connection variable. If the resulted query is successful then we echo (i.e. send back to frontend) the success message, else we return a message ‘Deletion failed’:
$sql = "DELETE FROM log WHERE file = '{$file}'";
if(mysqli_query($conn,$sql)){
$dataArray[0] = 'Deletion Successful';
$dataArray[1] = '200';
echo json_encode($dataArray);
}
else{
$dataArray[0] = 'Deletion failed';
$dataArray[1] = '401';
echo json_encode($dataArray);
}
  1. Close Connection
    Once we are done with our operation, then it is a good practise to close the database connection using this simple query:

    $conn->close();

Full code:

Here, we have added two nested deletion codes. It is used in a use case where we have to delete data from two different tables.

function onDeleteLogs(){
$servername = "localhost";
$username = "root";
$dbname = "<your_database_name>";
// Create connection
$conn = new mysqli($servername, $username,"", $dbname);
// Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    $obj = json_decode($_POST["data"]);
    $file = $obj->file;
    $date = $obj->date;
    $sql = "DELETE FROM transactions WHERE Date = '{$date}'";
    if(mysqli_query($conn,$sql)){
    $sql2 = "DELETE FROM log WHERE file = '{$file}'";
    if(mysqli_query($conn,$sql2)){
    $dataArray[0] = 'Deletion Successful';
    $dataArray[1] = '200';
    echo json_encode($dataArray);
    }
    else{
    $dataArray[0] = 'Deletion failed';
    $dataArray[1] = '401';
    echo json_encode($dataArray);
    }
    }
    else{
    $dataArray[0] = 'Deletion failed';
    $dataArray[1] = '401';
    echo json_encode($dataArray);
    }
}

Calling PHP to delete an entry in SQL from frontend

In above steps we have connected to SQL, fetched data and sent in response. The above function is only triggered once the UI calls it. In UI, we write given code to perform the required operation:

        onLogDelete: function(oEvent){
            var that = this;
var http = "http://";
var uri = http + "<location_of_your_php_file/name_of_your_php_file>";
            var data = JSON.stringify({
                "file": obj.file,
                "date": obj.date
            });
            // read msg from i18n model
            var sMsg = "Do you want to delete all data of chosen file";
            MessageBox.confirm(sMsg, function (rValue) {
                if (rValue === "OK") {
                    $.ajax({
                        url: uri,
                        type: "POST",
                        data: {
                            method: "onDeleteLogs",
                            data: data,
                        },
                        dataType: "json",						
                        success: function (response) {
                            if(response[1] === "401"){
                            MessageBox.error(response[0]);	
                            }
                            else{
                            MessageBox.success(response[0]);
                            that._onObjectMatched();
                            that.getOwnerComponent().getModel("appConfigModel").setProperty("/logTableCount", 0);	
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            MessageBox.error("Unable to Delete Log Data")
                        }
                    });
                }
            });
        }

 

Author

0 Comments

Submit a Comment

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

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

Author