Nid Moass
Nid Moass

Reputation: 19

PHP Delete not working as I would I like

Can someone help me. My delete code below works, but it's deleting the most recent Favorited file and not the specific file chosen. Here's the code:

while($row=$query->fetch())
{

$id=$row['id'];
$vid=$row['thread_id'];
$preview=$row['preview'];
$tt=$row['thread_title'];
$fav=$row['fav'];

$List.='<form action="" method="POST" id="postForm">
<div class="LISTT"><a href="VP2.php?id='.$vid.'">'.$preview.'</a><br/><label     id="pwords">'.$tt.'</label><br/>
<input type="submit" name="submit" value="Remove" id="DeleteButton"/>
</div></form>'; 

if(isset($_POST['submit']))
{
$query=$db->prepare("DELETE FROM favorite WHERE thread_id=:thread");
$query->execute(array(':thread'=>$vid));
}

}

Upvotes: 1

Views: 73

Answers (2)

DC-
DC-

Reputation: 807

The reason for this is because you have the If statement in your while loop. The logic in the code you have given is to delete records when $_POST['submit'] is set. So it will follow the loop to delete the records and not a specific record.

You need to pass the id you want to delete to the user, as you are using form to do this, have a hidden field with the id.

if(isset($_POST['submit']))
{
    $query=$db->prepare("DELETE FROM favorite WHERE thread_id=:thread");
    $query->execute(array(':thread'=>$_POST['id']));
}

while($row=$query->fetch())
{

    $id=$row['id'];
    $vid=$row['thread_id'];
    $preview=$row['preview'];
    $tt=$row['thread_title'];
    $fav=$row['fav'];

    $List.='<form action="" method="POST" id="postForm">
<div class="LISTT"><a href="VP2.php?id='.$vid.'">'.$preview.'</a><br/><label     id="pwords">'.$tt.'</label><br/>
<input type="submit" name="submit" value="Remove" id="DeleteButton"/>
<input type="hidden" name="id" id="id" value="'.$id.'" />
</div></form>'; 

}

Upvotes: 1

EdC
EdC

Reputation: 21

You need to add a hidden form field that contains the Thread ID into your form, then read that back in your form handler, something like this:

while($row=$query->fetch())
{
$id=$row['id'];
$vid=$row['thread_id'];
$preview=$row['preview'];
$tt=$row['thread_title'];
$fav=$row['fav'];

$List.='<form action="" method="POST" id="postForm">
<div class="LISTT"><a href="VP2.php?id='.$vid.'">'.$preview.'</a><br/><label id="pwords">'.$tt.'</label><br/>
<input type="hidden" name="thread" value="' . $vid . '" />
<input type="submit" name="submit" value="Remove" id="DeleteButton"/>
</div></form>'; 

if(isset($_POST['submit']))
{
$id = $_POST["thread"];
$query=$db->prepare("DELETE FROM favorite WHERE thread_id=:thread");
$query->execute(array(':thread'=>$id));
}
}

Upvotes: 1

Related Questions