PHP While Statement Delete only one row from table Mysql PDO

7
January 12, 2019, at 02:20 AM

I have a while statement and a PDO statement to delete one row if someone clicks the delete button.

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.

Answer 1

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.

Answer 2

No need while loop just pass single company id and delete via ajax or link or form post method

READ ALSO
How do I convert a number enum column to tinyint?

How do I convert a number enum column to tinyint?

Developing in Laravel 57, using a MySQL database

35
Ask for a quick update method for records that containing duplicate values

Ask for a quick update method for records that containing duplicate values

I have a table with millions of records, but each object could have multiple columns that share the same values while some other columns have different values

38
How to enter username in form and then search in database to produce if else statement

How to enter username in form and then search in database to produce if else statement

How would I get the $UN Variable to be set by the input provided by the formThen use the variable to search in the database to provide a users details

20