Simon
Simon

Reputation: 121

Delete button which deletes database row

I just made a php function

function deletebooking($orderID){

    $sql="DELETE FROM bs_reservations WHERE id='".$orderID."'";
    $result=mysql_query($sql) or die("oopsy, error when tryin to delete events 2");

}

I have a .php file which process a submitted form and then displays a HTML page. How do i add a delete booking button which calls the above function to the HTML page. The $orderID variable is already set.

Suggestions Welcome

Upvotes: 4

Views: 32034

Answers (4)

Geo
Geo

Reputation: 3200

I would also suggest adding a reload in your function this way the id doesn't stay in the url after the delete action.

$page = 'current.php';

if($_GET['del'])
   {
    deletebooking($orderID,$page);

   }  

function deletebooking($orderID,$page){

    $sql="DELETE FROM bs_reservations WHERE id='".$orderID."'";
    $result=mysql_query($sql) or die("oopsy, error when tryin to delete events 2");
    header('Location: '.$page, true, 303);
}

Upvotes: 0

Cal
Cal

Reputation: 7157

Here's an example page, let's call it page.php:

<?
    include "includes/dbconnect.php";
    include "includes/functions.php";

    if ($_POST['delete']){
        deletebooking(intval($_POST['delete']));
        echo "deleted!";
        exit;
    }
?>
<form action="page.php" method="post">
<input type="hidden" name="delete" value="<?=intval($orderID)?>" />
<input type="submit" value="Delete order #<?=intval($orderID)?>" />
</form>

The one file is both the form that you present to the user and the code that performs the actual deletion. We pass the ID of the record to be deleted as a hidden form value.

Upvotes: 2

Varada
Varada

Reputation: 17042

You can use a javascript code on the button which you click to delete the record as

<input type="button" name-"abc" id="abc" onclick="return Deleteqry(<?php echo $orderID ?>);"/>

Now you can write the javascript function inside the <head></head> as

function Deleteqry(id)
{ 
  if(confirm("Are you sure you want to delete this row?")==true)
           window.location="yourpagename.php?del="+id;
    return false;
}

Now you can write on the top of your page as

 if($_GET['del'])
   {
    deletebooking($orderID);

   }    

Here we are using a message alert for the conformation of the deletion using the javascript alert box...

Upvotes: 6

Explosion Pills
Explosion Pills

Reputation: 191749

Two things. First, look up "SQL injection." Sanitize the input of your query.

Second: don't do this. It's not a good idea. If the orderID is already set on the page, then presumably it can be changed by the user to anything they want and then deleted. Instead, you should associate the orderID deleting with authentication, or have a status for order IDs instead ("Deleted," for instance) that prevents loss of any data.

Other than that, the other answer will do what you need. This is not complicated.

Upvotes: 3

Related Questions