0

i'm trying to delete from the database multiple rows using checkboxes.

I have an html table inside a foreach loop to seek the table values.

And i want to put a delete button inside this table to delete all the values from a certain row.

But i dont know how to do that, i'm using this code:

if (isset($_POST['delete']) && (!empty($_POST['checkbox']))){
$del_id = $_POST['checkbox']; 

foreach($del_id as $value){
   $sql = "DELETE FROM my_table WHERE id='".$value."'";
   $result = mysql_query($sql);
}
}

And i have this code inside the foreach loop

<td><input style='width: 50px;' class='delete' value='delete' name='checkbox' type='checkbox'/></td>

<input type='hidden' name='id' value=".$key['job_id']." />
0

2 Answers 2

2

you need to change your this code from

<td><input style='width: 50px;' class='delete' value='delete' name='checkbox' type='checkbox'/></td>

to something like

<td><input style='width: 50px;' class='delete' value='delete' name='checkbox[]' type='checkbox'/></td>

see the difference between name='checkbox' and name='checkbox[]' and then in your php code .. write something like this

print_r($_POST);

you will get all the values .. try this .

Sign up to request clarification or add additional context in comments.

Comments

0

You should treat the checkbox as an array:

<input style='width: 50px;' class='delete' value='delete' name='checkbox[]' type='checkbox'/>

Also, instead of creating a new MySQL statement for each checkbox value received, you can use the IN() command:

if (isset($_POST['delete']) && (!empty($_POST['checkbox']))){
$del_ids = implode(',', $_POST['checkbox']); 

$sql = "DELETE FROM my_table WHERE id IN('".$del_ids."')";
}

However, I strongly suggest using prepared statements. You also don't seem to sanitize the values in the $_POST variable — very dangerous.

Comments

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.