Reputation: 13
I have a while statement and a PDO statement to delete one row if someone clicks the delete button.
$companies = $db->query("SELECT * FROM companies LIMIT 50");
while($result = $companies->fetch()) {
$delete = $db->prepare("DELETE from companies WHERE id=?");
$response = $delete->execute(array($result['id']));
}
}
For example:
Company 1 DELETE
Company 2 DELETE
If someone clicks that delete button, I want to delete the company that it is attached to. Right now, when I execute this code and click delete for only one company, it deletes every company in the table.
Upvotes: 0
Views: 201
Reputation: 259
No need while loop just pass single company id and delete via ajax or link or form post method
Upvotes: 0
Reputation: 211680
Your code is in the middle of a loop and calls DELETE
on each record it finds. Not surprisingly, it deletes all companies.
Normally what you do is delete one and only one:
$delete = $db->prepare("DELETE from companies WHERE id=?");
$response = $delete->execute(array($_POST['id']));
Where $_POST['id']
represents the posted id
parameter. The reason POST is used is because some browsers will try and be helpful and pre-fetch any GET links. This means they'll helpfully delete everything.
The convention is to use POST since browsers don't trigger those automatically.
Tools like jQuery make it easy to POST links with $.post
and such. For example:
<a href="/delete" data-id="3" data-method="post" class="btn btn-primary">Delete</a>
Where you can then bind automatically to all of these "post" buttons using something like this:
$(function() {
// Augment all postable links with a click handler
$('a[data-method="post"]').click(function() {
$.post($(this).attr('href'), {
id: $(this).attr('data-id')
});
return false;
});
});
Where using unobtrusive-JavaScript principles you can add this fairly seamlessly.
Upvotes: 0