Hi, I'm trying to delete many items form a database at ones using checkboxes but is not working. Here\'s what I have.. $id = $r["id"]; //The $id comes from a database. //Each user has a unique ID. <input type="checkbox" name="user[]" value="'.$id.'" /> for($i=0;$i<$count;$i++){ $del_id = $user[$i]; $sql = "DELETE FROM users WHERE id='$del_id'"; $result = mysql_query($sql); } PHP: I got it from another website, I know I'm missing something. Is not giving me any errors it just not doing anything. Help please Thanks in advance
Drop that loop and do: $ids = array_map('intval', (array)$_POST['user']); $ids = implode(', ', $ids); mysql_query("DELETE FROM `users` WHERE `id` IN({$ids})") OR die(mysql_error()); PHP:
try this code for the loop for($i=0;$i<sizeof(user);$i++){ $del_id = $user[$i]; $sql = "DELETE FROM users WHERE id='$del_id'"; $result = mysql_query($sql); }
^ That's not going to work either. (Small typo in your code). And anyway, don't use a loop. Why stress the server with multiple queries when you can do it with a single one? (It's less code too......)
Lets bring this thread back to life! I am having a few issues with this. I love the idea of using nico's efficient script, but I am fairly new to php and programming in general so while I am sure the problem is fairly silly and obvious, I have been staring all night and I just can't figure it out. Here is my code for the checkboxes and generating the id's: $dbc = mysqli_connect(my connection info) or die ('sorry its broke'); $data = mysqli_query($dbc, $query); $row = mysqli_fetch_array($data); $id = $row['message_id']; echo '<input name="deletebox[]" type="checkbox" value="'.$id.'">'; Code (markup): Here is my form button code <form method="post" action="deletemessages.php"> <input name="delete" type="submit" value="Delete Checked"> Code (markup): And here is deletemessage.php <?php $dbc = mysqli_connect(' all my database connection info') or die ('not working'); $ids = array_map('intval', (array)$_POST['deletebox']); $ids = implode(', ', $ids); $query = "DELETE FROM private_messages WHERE message_id IN({$ids})"; mysqli_query($dbc, $query); ?> PHP:
hi just write a foreach loop or for loop then append the each value with comma inside the loop.so you will get the string as 2,3,4 (example),then pass it it your delete query.it will work out
I know I could do a loop but I was first trying to get it to work using the method nico suggested. Anyone see where I am going wrong?
Have you done some debugging to see what is actually in $ids after implode them? Also do a print_r($_POST); and check the data that gets submitted.
have not debugged for $ids The print revealed this: Array ( [deletebox] => Array ( [0] => 3 [1] => 2 [2] => 1 ) [delete] => Delete Checked )