根据所选复选框从数据库中删除行

时间:2015-09-09 08:37:23

标签: php mysql

我正在尝试删除数据库中的某些行,无论是否通过单击其复选框选中它们。我正在使用PK(一个自动递增的ID来标识选择了哪一行)来删除它。但我没有删除它。请帮忙。我的语法有什么问题。

$conn = new PDO('mysql:host=localhost;dbname=jr', 'root', 'Js');
    $conn->exec("set names utf8");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $num_rows = $conn->query('SELECT COUNT(*) FROM employees')->fetchColumn(); 


    $stmt = $conn->prepare("SELECT appendtest.ID,appendtest.EvaluationType,appendtest.EvaluatorAF,appendtest.EvaluatedAF FROM appendtest");
    $stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
    $stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll();

    $selectedtable = "<table class='sortable'><tr><th>Select</th><th>Evaluation Type</th><th style='width:200px'>Evaluator AFNumber</th><th style='width:150px'>Evaluated AFNumber</th></tr>\n";



    foreach($result as $row) {



        $selectedtable .= "<tr><td><input type='checkbox' name='del' value='$row[0]' style='margin:10px;'></td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>\n";



    }
    if(isset($_POST['del']))
            {   

                $sql="DELETE  FROM appendtest  WHERE id = '$row[0]'";
                mysqli_query($con,$sql);

         }
    $selectedtable .= "</table>\n";
         $selectedtable .= "<input type='submit' name='del' value='Delete' style='width:80px; height:30px; text-align:center; padding:0px;'>\n"; 

2 个答案:

答案 0 :(得分:0)

首先,改变

<input type='checkbox' name='del' value='$row[0]' style='margin:10px;'>

<input type='checkbox' name='del[]' value='$row[0]' style='margin:10px;'>

并将“提交”的名称更改为&#39; del&#39;作为示例&#39; sub&#39;

然后将操作更改为:

if ($_POST['sub'] && count($_POST['del']) > 0) {
    $ids = implode(',', $_POST['del']);
    $sql = "DELETE  FROM appendtest  WHERE id IN ('$ids')";
    mysqli_query($con, $sql);
}

如果你想添加一些安全措施:

$ids = implode(',', array_map('intval', $_POST['del']));

答案 1 :(得分:0)

HTML复选框代码

<form method="post" action="filename.php" >
<input type='checkbox' name='del[]' id='del[]' value='$row[0]' style='margin:10px;'>
<input type="submit" name="submit" value="submit" >
</form>

PHP代码

 if(isset($_POST['submit']))
 {
    $checkbox = $_POST['del'];

    for($i=0;$i<count($checkbox);$i++)
    {
       $id = $checkbox[$i];

       $sql1 = "DELETE  FROM `tablename` WHERE `id` =' $id' ";
       mysqli_query($con, $sql1) ;
    }
 }