Wednesday 5 September 2018

Action to delete the process database in the same PHP page with a post

I'm building PHP application for process employee leave records. In this application the main screen populate database records and action buttons. when user click the action button it take the database id from the table and go through another file to delete that record and then redirect back to the same page. This mechanism implemented using HTML _GET method. that means anyone can see the row ID in the URL feed and if anyone request this url with different row ID, PHP file delete the record since any other security measures not taken place in to prevent that. and also this application not using any kind of session.
this is my href code for the task I mentioned above.
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";

and this is my rejectone.php code
<?php
$lid =$_GET['id'];
include 'database.php';
$accval = "Accept";
try {
   $query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = '$lid'";
    $stmt = $con->prepare( $query );
    $stmt->bindParam(1, $id);
    $stmt->execute();
}

catch(PDOException $exception){
    die('ERROR: ' . $exception->getMessage());
}
header( "refresh:0;url=bs.php" );
?>

I have two questions
1.) How can I run the rejectone task inside the same PHP file without redirecting to another PHP file
2.) How can I use HTML _POST method instead of get method to transfer data if I still use jejectone.php file
thanks!!

First of all change your line:
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";

to
echo '<a href="javascript:;" class="btn btn-danger btn-xs m-r-1em delete-item" primary-key="'.$lvid.'">Cancal</a>';

If you haven't included jQuery on your site, you can do it by adding this script to your page, just before closing </head> tag
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>

Add this JavaScript file to the bottom of your page, just before closing </body>
<script type="text/javascript">

$(document).ready(function(){
    $(document).on('click', '.delete-item', function(e){

        e.preventDefault();
        if(!confirm('Are you sure you want to delete this item?')) return false;

        $.post('bs.php', {'id': t.attr('primary-key'), 'delete_item': 1}, function(e){
            window.location = 'bs.php';
        })

    })
})

</script>

Copy your rejectone.php to bs.php, but make these changes:
if(isset($_POST['delete_item']))
{
    $lid = (int)$_POST['id'];
    include 'database.php';
    $accval = "Accept";
    try {
       $query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = :lid ";
        $stmt = $con->prepare( $query );
        $stmt->bindParam(':lid', $lid );
        $stmt->execute();
    }

    catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }

}

0 comments:

Post a Comment