如何从db中删除已检查的行

时间:2014-10-22 10:04:47

标签: php checkbox delete-row sql-delete

我有这个删除sql但似乎无法找出它无法正常工作的原因:/

尝试删除已检查的行后,if($ result)会重新加载页面,但行仍然存在...:/

有人可以帮帮我吗? 我错过了什么?

<form name="delete_posts" method="post" action="">
        <table class="all_posts">
            <tr>
                <td class="checkbox"><input type="checkbox" name="select_all" id="select_all" /></td>
                <td class="post_title">Title</td>
                <td>Auther</td>
                <td>Posted</td>
                <td>Updated</td>
                <td>Category</td>

            </tr>
            <tr><td class="delete_posts" colspan="6"><input name="delete" type="submit"     
id="delete" value="delete"></td></tr>

<?php 

    $post_set = get_all_posts();
    while ($row = mysqli_fetch_array($post_set)){

        echo "<tr>
                <td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=".$row['id']."></td>
                <td><a href=\"edit_post.php?edit=".$row['id']."\">" .$row['title']. "</td>
                <td>Auther</td>
                <td>".date("d. M. 'y", strtotime($row["date"]))."</td>
                <td>Update Date</td>
                <td>".str_replace("_"," ",$row['category'])."</td>
            </tr>";}


// Delete Posts

if(isset($_POST['delete'])){
    $checkbox = $_POST['delete'];
    $count = count($checkbox);
    for($i=0;$i<$count;$i++){
    $del_id = $checkbox[$i];
$sql = "DELETE FROM posts WHERE id = $del_id ";
$result = mysqli_query($connection, $sql);
}
// if successful redirect to delete_multiple.php 
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=posts.php\">";
}
}
?>

</table>                
</form>

Thanx帮助

干杯 克里斯

1 个答案:

答案 0 :(得分:0)

我认为您的代码中有一个错误,您在其中检索选中的行:而不是获取复选框值($checkbox = $_POST['checkbox'];),您将获得删除值($checkbox = $_POST['delete'];)。

以下是更正的部分:

if(isset($_POST['delete'])){
    $checkbox = $_POST['checkbox'];
    $count = count($checkbox);
    for($i=0;$i<$count;$i++){
    $del_id = $checkbox[$i];
$sql = "DELETE FROM posts WHERE id = $del_id ";
$result = mysqli_query($connection, $sql);
}