'Deleting a database row on front end of Wordpress site

I have created a front end page on my Wordpress site where I can submit data through a form, and it will display all the data in a table on the same page. I would like to have a delete option for each row but I am not sure which way to go.

The code I am using to display the database information works fine.

        /* Displays Table and Data*/
        foreach($cogs as $cogs){

            echo "<tr>";

                echo "<td>".$cogs->id."</td>";

                echo "<td>".$cogs->date."</td>";

                echo "<td>".$cogs->source."</td>";

                echo "<td>".$cogs->items_purchased."</td>";

                echo "<td>".$cogs->receipt_total."</td>";

                echo "<td>" "</td>";
            
            echo "</tr>";

        }

In the line after "receipt_total," what code should I write? Should I include an anchor tag and link the delete button to another page? I have tried an HTML link, and a HTML button. My problem is making the button or link delete the row from the database. Someone suggested this code, but I am not sure I am using it right. My gut instinct is to place this code in my functions.php file, but I am not sure.

<?php
  if(isset($_GET['id']) &&!empty($_GET['id'])){
    $id = $_GET['id'];
    $table = 'cogs';
    $wpdb->delete( $table, array( 'id' => $id ) );  
    wp_redirect('URL');
}
?>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source