0

I am trying to delete a row based on its ID

HTML:

<form action=""  method="post">
<input type="submit" name="delete" value=" delete "/>
</form>

PHP:

        $u = $_REQUEST['edit']; // contains the ID of row to be deleted

        if(isset($_POST['delete'])){
            $db->exec("DELETE FROM infos WHERE id = '$u'");
        }   

Nothing happens when the delete button is pressed. How can I fix this?

thenoob
  • 67
  • 9
  • Your code is vulnerable to SQL injection attacks. You should use [mysqli](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) or [PDO](http://php.net/manual/en/pdo.prepared-statements.php) prepared statements as described in [this post](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky Apr 13 '17 at 17:13
  • 1
    You have no input with `name="edit"` in the form. – Barmar Apr 13 '17 at 17:15
  • where is edit element? – lalithkumar Apr 13 '17 at 17:16
  • @Barmar what will that do? – thenoob Apr 13 '17 at 17:22

2 Answers2

3

You need an edit input whose value is the ID your want to delete.

<form action=""  method="post">
<input type="hidden" name="edit" value="<?php echo $id; ?>">
<input type="submit" name="delete" value=" delete "/>
</form>

Replace $id with the actual variable you use in the script that creates the form.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Did you replace `$id` with the actual variable from your script? – Barmar Apr 13 '17 at 17:25
  • what if i wanted to redirect to another page when the delete button is clicked also? When I try to change action it goes to that page but noting gets deleted – thenoob Apr 13 '17 at 17:30
  • The script that processes the form should send an HTTP redirect to the new page, using `header("Location: newURL")` – Barmar Apr 13 '17 at 19:10
1
<form action=""  method="post">
<input type="hidden" name="edit" value="<?php echo $id; ?>">
<input type="submit" name="delete" value=" delete "/>
</form> 

After that try this

$u = $_REQUEST['edit']; // contains the ID of row to be deleted
if($u){
   $db->exec("DELETE FROM infos WHERE id = '$u'");
}

Apparently when you are submitting only you posting data to php file.So you can check like this is enough.you told delete not happening so that i am posting this answer

lalithkumar
  • 3,480
  • 4
  • 24
  • 40
  • what if i wanted to redirect to another page when the delete button is clicked also? When I try to change action to a page, it goes to that page but noting gets deleted – thenoob Apr 13 '17 at 18:07
  • check edit element keeps value or not by change type='hidden1'..if not it wont be delete – lalithkumar Apr 13 '17 at 18:10
  • so theres no way I can delete and direct to another page? – thenoob Apr 13 '17 at 18:17