1

I have to POST selected input checkboxes using jquery to PHP. I inserted the array to an hidden input field. When I receive the array in PHP, only one userid is deleted. But I want all the selected userid to be deleted from the database.

My jquery code is:

$("#delSelected").click(function(){
        var checks = [];
        $.each($("#userList input:checked"), function(){            
            checks.push($(this).val());
        });
        $("#modal-user").html("Selected Users");
        $("#modal-footer").html("<form action='' method='post'><input type='hidden' name='checkboxes[]' value='"+ checks +"'><button class='btn btn-warning btn-sm' type='submit' name='submit'>Yes Delete</button></form><button type='button' class='btn btn-secondary btn-sm' data-dismiss='modal'>Cancel</button>");
    });

My PHP code is:

if(isset($_POST['submit'])){
    $checkboxes = $_POST['checkboxes'];
     foreach($checkboxes as $uId){
        mysqli_query($con, "DELETE FROM users WHERE id = '$uId' ");
     }
}
9
  • have you got all user id in $uId this variable in checkbox loop? Commented Apr 13, 2019 at 8:03
  • yes when I print $uId within foreach loop its outputing like : 32,44,56 Commented Apr 13, 2019 at 8:17
  • okay, so please double check with the table name and column name or try to delete with in query also debug with print query in loop and execute on mysql Commented Apr 13, 2019 at 8:22
  • So, your $checkboxes reads "2,4,5,6", then what does the SQL look like? DELETE FROM users WHERE id = '2,4,5,6'. And? Is this a valid SQL syntax? Commented Apr 13, 2019 at 8:24
  • No, that's not the valid syntax. That's the problem I am facing. I am expecting, from each loop: DELETE FROM users WHERE id = 2; then DELETE FROM users WHERE id = 4 and so on Commented Apr 13, 2019 at 8:35

1 Answer 1

1

you should set the array index.

if(isset($_POST['submit'])){
    $checkboxes = $_POST['checkboxes'];
     foreach($checkboxes[0] as $uId){
        mysqli_query($con, "DELETE FROM users WHERE id = '$uId' ");
     }
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Rishi what is your print_r($checkboxes); result?
before doing explode: - Array ( [0] => 50,34 )
@Rishi then please try with this $checkboxesArray = explode(',', $checkboxes[0]); answer updated
Fine I'm happy that I can help

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.