使用复选框从表中删除多条记录(行)


Deleting multiple records(rows) from tables using checkboxes

尝试使用复选框删除多行。首先,我生成与复选框列的目录表。然后将数据发布到php端。问题是,php端返回到当前页面。这意味着所有操作都成功完成,页面返回用户。但没有成功。php日志没有错误,MySQL有问题。我在$delete=$_POST['delete'];之后又尝试了print_r ($_POST['checkbox']); die();。它给了我类似于Array ( [0] => on [1] => on )的结果,我的代码有什么问题?

我的HTML标记看起来像这样

<?php
$result = $db->query("SELECT id, name, showinmenu FROM menu") ;
$num=$result->num_rows;
if ($num>0) {
?>
    <form method="post" action="processor/dbdel.php">
    <div style="overflow-y: auto; overflow-x: hidden; height:500px">
    <table id="list" class="features-table">    
            <thead>
                <tr>
                    <th>#</th>
                    <th style="min-width:80px;"  class="name">Ad (menyuda işlənən)</th>
                    <th>Sil</th>
                </tr>
            </thead>
            <tbody>
<? 
while ($row = $result->fetch_object()) {
echo '<tr>
<td>'.$row->id.'</td>
<td><a href="'.$wsurl.'admin/?page=edit&id='.$row->id.'">'.$row->name.'</a></td>
<td><input type="checkbox" name="checkbox[]" method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
</tr>';
    }
    // when the loop is complete, close off the list.
    echo "</tbody>  <tr id='noresults'>
        <td style='text-align:center' colspan='9'>Nəticə yoxdur</td>
    </tr></table>
    </div>
    <p style='text-align:center;'>
    <input id='delete' type='submit' name='delete' value='Seçilənləri sil'/>        </p>
    </form>";
    }
    ?>
这里是我的PHP代码
<?php
    require '../../core/includes/common.php';
        $delete=$_POST['delete'];
        if($delete) // from button name="delete"
        {
        if (is_array($_POST['checkbox'])) 
        foreach($_POST['checkbox'] as $del_id) {
                $del_id = (int)$del_id;
                $result=$db->query ("DELETE FROM menu WHERE id = '$del_id'") or die($db->error);
                $result2=$db->query ("DELETE FROM pages WHERE id = '$del_id'") or die($db->error);
            }
                if($result2)
            {   
                    header("location:".$wsurl."admin/?page=db");    
                }
                else
                {
                    echo "Error: ".$db->error;
                }
        }
    ?>

你的代码简直是一场灾难。

1)使用echo与重复字符串连接输出html。查找HEREDOCs,双引号字符串,或者简单地跳出php模式(?>)来输出html。

2)通过查找表单字段来检查POST。如果你想确保你在POST的情况下,然后做if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }代替。这是100%可靠的,并且不依赖于特定表单字段的存在(或不存在)。如果数据是通过post提交的,则该语句的值将始终为true。

3)你盲目地将用户提供的数据嵌入到SQL查询字符串中。阅读SQL注入攻击,然后考虑如果有人入侵您的表单并提交一个复选框值' or 1'会发生什么-与复选框表的内容说再见。

4)您的复选框输出行中似乎有一个偏离的":

[...snip...] method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
                                                               ^--here

几乎肯定会"破坏"你的表单,并导致后续的标签属性被误解。

5)从好的方面来说,我必须给你这么多——你至少检查了你的两个删除查询的查询错误,这总是很高兴看到的。然而,这只是一大堆缺点中的一个小优点。