1

I have a form that includes a delete button. I want the user to be able to select all the items they wish to delete at once. I managed to get the echo to display but the items still remain on the page. Can you please point out why that happens? Any help is appreciated!

Delete button:

  <input name="del_btn" type="submit" value="Delete">

The check:

   if (isset($_POST['del_btn']) && $_POST['del_btn']){
        for($i = 0; $i < count($_POST['checkbox']); $i++){
            if (isset($_POST['checkbox'])) {
                mysql_query("DELETE FROM `posts` WHERE `id` = '" . $_POST['checkbox'][$i] . "' LIMIT 1");   
                echo 'deleted';
            }
        }
 }

the items' checkbox:

<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />
5
  • Your form is displaying the post values. Can you display the code for some of your inputs in the view file? Commented Mar 4, 2014 at 0:26
  • the view field is just a div that is inside a while loop that retrieves the necessary variables of that post (id, title..) Commented Mar 4, 2014 at 0:40
  • Ok, so refer to #1 in my answer below. Create a redirect at the end of the if statement. I wasn't sure if there were also text fields on the page. I understand what you're saying now. Another option is to use jquery to add hide rows that are checked. Commented Mar 4, 2014 at 0:41
  • Asking if (isset($_POST['checkbox'])) when you have already used that variable in a reading context the line before does not make any sense. Commented Mar 4, 2014 at 1:02
  • 1.Please echo the whole delete query but not 'deleted', and I think you will know what's going wrong. May be there's something with your parameters, especially $_POST['checkbox']. 2. Have you used InnoDB with transaction? If you started a transaction and don't commit it, nothing will happens to your data. Commented Mar 4, 2014 at 1:20

4 Answers 4

2

This really depends on how variables are defined in your controller, and how they are displayed in your view file.

If you want to hide/clear the values in your forms you can:

  1. Reload the page: create a redirect at the end of your if (isset($_POST['del_btn']) && $_POST['del_btn']){ statement that sends the user back to the new page.
  2. Use jQuery to hide divs where the checkbox is checked.
  3. Redefine variables in your controller after the post to be NULL.
  4. Add a ternary operator to your values in the view so for example <input name="form_input" type="text" value=<?=isset($_POST['del_btn'] ? NULL : $form_input?>> which means that the form will display as NULL when the del_btn is submitted.
Sign up to request clarification or add additional context in comments.

7 Comments

Not clear or hide, I want to delete from the database forever kind of deal. From what I understand, your suggestions are for hiding it from the viewing field right?
Yes, they will be deleted from the database using the mysql_query("DELETE FROM posts WHERE id = '" . $_POST['checkbox'][$i] . "' LIMIT 1"); But the page doesn't reload automatically on submit. This assumes that your query is working properly.
doing a redirect would be the same as if I refresh the page right, so I tried both and in both cases the post is still there after the delete button is clicked
that is weird, I cannot find the problem in the code :/
Are the values being deleted from the database? Does the query work properly when you run it directly on your database?
|
0
<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />

I think you must put something like

<input name="checkbox[]" type="checkbox" value="<?php echo $id; ?>" />

Note the word "value" instead of "id". You are putting the ID in the id attribute. It is to assign a specific target if you want to take the value. (You can use Javascript or JQuery to do this).

In your case, use the tag "value" to ensure that you have correct ID value for your check box. Echo the query and not the word "deleted".

$queryDel =  "DELETE FROM posts WHERE id = " . $_POST['checkbox'][$i] . " LIMIT 1";
echo $queryDel;

Please beware of SQL Injection if you are using mysql_query(). Use mysqli instead. Use prepared statement to prevent it or at least provide some white list or validation.

Hope this helps. Thank you.

Comments

0
 <input name="checkbox[]" type="checkbox" value ="<?php echo $id; ?>" id="<?php echo $id; ?>" />

Try this it will work. and check the value print_r($_POST) you will able to see all the post value and able to get right value.

1 Comment

i did the print_r and got Array ( [del_btn] => Delete Selected [checkbox] => Array ( [0] => 267 ) ) for every item on the list
0

When you are using checkbox your element became an array than you can use multiple approaches:

Use ajax (example with jQuery) to avoid submit:

<script>
$(document).ready(function() {
   $('[name="del_btn"]').click(function() {
      $.post('/my/action.php', $('form').serialize(), function(r) {
         if (r.success) {
             alert('deleted....');
         } else {
             alert('error');
         }
      },'json');
      return false; // prevent submit
   });
});
</script>

Than you can simplify your code with this:

<?php
if (isset($_POST['checkbox']) && count($_POST['checkbox'])){
    $c = implode(',', array_map('intval', $_POST['checkbox'])); // sanitize data
    $r = mysql_query("DELETE FROM `posts` WHERE `id` IN(" . $c .")");
    echo json_encode(array('success' => $r));
}

1 Comment

I was hoping to do it with php only as I am not really good with jquery

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.