使用复选框删除记录/多个记录(PHP / MYSQL)

时间:2011-05-11 16:37:58

标签: php mysql

请有人帮我解决这个问题。我是php / mysql / stackoverflow的总菜鸟。

我正在尝试从mysql数据库中删除一条记录 - 这是我的代码到目前为止....

//Includes db connect file


// Display the student(s) within the html table
      while($row = mysql_fetch_array($result))

 {
echo "<tr><td align='centre' bgcolor='#693'><input name='checkbox[]' type='checkbox' id='checkbox[]' value=' $rows'Delete record?'>";
echo "<td> $row[studentid] </td> <td> $row[password] </td>";
echo "<td> $row[dob] </td><td> $row[firstname] </td>";
echo "<td> $row[lastname] </td><td> $row[house] </td>";
echo "<td> $row[town] </td><td> $row[county] </td>";
echo "<td> $row[country] </td><td> $row[postcode] </td>";
}echo "</table>";

echo "<tr><td colspan='11' align='center' bgcolor='#FFFFFF'><input name='delete' type='submit' id='delete' value='Delete selected student(s)'></td>";
echo "</tr>";

?>

<?php


if($_POST['delete']) // from button name="delete"
 {
    $checkbox = $_POST['checked'];
    $countCheck = count($_POST['checked']);

    for($i=0;$i<$countCheck;$i++) {
        $del_id = $checkbox[$i];

    $sql = "DELETE FROM student WHERE  = $del_id";
    $result = mysql_query($sql);
    }
}


?>

4 个答案:

答案 0 :(得分:2)

$sql = "DELETE FROM student WHERE  = $del_id";

WHERE <something> = $del_id,您错过了<something>,大概应该是id

此外,您可能希望研究“SQL Injection”,“Prepared Statements”和“Input Sanitization”,因为您的代码目前尚未清理输入/输出或防止SQL注入。

答案 1 :(得分:1)

$sql = "DELETE FROM student WHERE  id= %d";
$sql = sprintf($sql,(int)$del_id);
$result = mysql_query($sql);

现在应该可行,除非你有其他错误

答案 2 :(得分:1)

有几点需要注意:

  1. 您的删除应该在输出之前。我之所以这么说是因为即使删除成功,它也会在删除实际触发之前再次出现,为您留下“Ghost”条目。
  2. 确保在处理数据库时清理用户的输入 - mysql_real_escape_string具有特定目的,尤其是在您不使用ADO时。或者,您可以使用$delete_id = (int)$checkbox[$i]之类的内容来确保它是一个整数值。
  3. 您的删除需要引用删除所属的where子句中的哪一列。通常这是表的主键。请务必将复选框的值更改为$row['id'](或任何键),然后在DELETE FROM student WHERE <column> = <checkbox_value>)
  4. 中重新引用该列

答案 3 :(得分:0)

LIVE DEMO

if(isset($_POST['delete']))
{
$check=$_POST['check'];
$count=count($check);
for($i=0;$i<$count;$i++){
$del_id = $check[$i];
$delete=mysql_query("delete from emp where id='$del_id'") or die(mysql_error());
}
if($delete){ $msg2="Successfully Deleted!!";}

}