使用复选框从db中删除多个数据

时间:2012-08-31 17:13:27

标签: php database sql-delete

如何使用复选框从表中删除多个数据? 我有这段代码:

<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>

这是coments-del.php,您在上面的脚本中提交表单后会被带来。

头部是:

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

正文是代理删除的代码。

<?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.";
}

?>

2 个答案:

答案 0 :(得分:1)

第一步是将复选框名称设为数组。

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

当您的脚本收到帖子时,将该数组解析为适当的sql子句。

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

最后将该子句放入where子句中的查询中。

答案 1 :(得分:0)

我不确定我是否理解你,但我通常会将PK保存到数组中,然后执行以下操作:

<?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).')');
}
?>