0

How to delete multiple data from table with checkbox? I have this code:

<form id="prefForm" action="coments-del.php" method="post">

<?

$result = mysql_query("SELECT * FROM comments");      
$myrow = mysql_fetch_array($result);

do
{
    $res = mysql_query("SELECT title FROM data WHERE id=$myrow[post]");
    $row = mysql_fetch_array($res);
    printf ("
         <tr>
           <td>
                <input type='checkbox' name='id' value='%s'  />
                </td>        
                <td>%s</td>
           <td>%s</td>
                <td>%s</td>
         ",$myrow["id"],$myrow["id"],$myrow["author"],$myrow["text"]);
}
while ($myrow = mysql_fetch_array($result));
?>

<input name="submit-button" type="submit" value="Delete" />
</form>

Here is the coments-del.php where you get brought after submiting form in script above.

In the head is:

if (isset($_POST['id'])) { $id = $_POST['id']; }

At the body is the code that proccess the deleting.

<?php 
if (isset($id)) {
    $result = mysql_query ("DELETE FROM comments WHERE id='$id'");

    if ($result == 'true') {echo "Comment Deleted!";}
    else {echo "Error: Nothing was deleted!";}

} else {
    echo "Unknown Error! Contact Administrator.";
}

?>
1

2 Answers 2

1

First step is to make your checkbox name an array.

<input type='checkbox' name='id[]' value='%s'  />

And when your script receive the post, parse that array out to the appropriate sql clause.

$clause="";
if (isset($_POST['id'])) { 
   foreach ($_POST['id'] as $p)
   $clause.="id='$p' OR"; 
}
$clause=substr($clause,0,-2);

Finally put the clause into the query in the where clause.

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

3 Comments

so i have to put your php code in the code after submiting? This one - coments-del.php ?
first part in the html form creating the post, and second part in the comments-del.php.
but it doesnt work. I pasted last part in comments-del.php and it didnt work.
0

I'm not sure if I understand you but I usually save PKs into an array and then do something like this:

<?php
//... process your ids (eg. filter out not numerical values) and save into an array

if(count($ids_array)>0){
   mysql_query('DELETE FROM comments WHERE id IN ('.implode(',', $ids_array).')');
}
?>

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.