从表中删除1行,出现按钮问题

时间:2018-11-12 10:40:58

标签: php html sql

我正在处理一个较旧的项目。需要从数据库中删除特定行的小修正。有一个循环从数据库检索图像,并向其添加一个删除按钮。但是,当我单击“删除”按钮时,它将删除所有图像,而不是我单击的图像。因此,如果它检索5张图像。它删除5而不是我单击的1。 ps。(不要讨厌使用pls的旧版sql :)

$result = mysqli_query($con, "SELECT selfies.ID, selfies.afbeelding FROM selfies");
while($row = mysqli_fetch_array($result)){
    echo "<div class='results'>";
    $image = $row['afbeelding'];
    $image_src = "images/".$image;
    echo "<img class='selfiess' src='$image_src'>";
    echo "<br>";
    echo "<form method='post'><button type='submit' value='".$row['ID']."' class='button special big' name='removeSel'>Remove</button></form><br><br>";
    echo "</div>";
    if (isset($_POST['removeSel'])){
        $query = mysqli_query($con, "DELETE FROM selfies WHERE ID='".$row['ID']."' LIMIT 1");
        $result2 = mysql_query($query);
        header("Location: index.php?page=selfies");
    }
}

1 个答案:

答案 0 :(得分:-1)

根据我的评论...(您已经在while循环中编写了删除查询,并且还使用了$row['ID']。这意味着所有图像都将被删除。您应该在循环外编写delete查询并获取图像ID来自form submit

$result = mysqli_query($con, "SELECT selfies.ID, selfies.afbeelding FROM selfies");
while($row = mysqli_fetch_array($result)){
    echo "<div class='results'>";
    $image = $row['afbeelding'];
    $image_src = "images/".$image;
    echo "<img class='selfiess' src='$image_src'>";
    echo "<br>";
    echo "<form method='post'><input type='hidden' name'image_id' value='".$row['ID']."'><button type='submit' value='".$row['ID']."' class='button special big' name='removeSel'>Remove</button></form><br><br>";
    echo "</div>";

}
//here is delete image code outside of loop
        if (isset($_POST['removeSel'])){
            $query = mysqli_query($con, "DELETE FROM selfies WHERE ID='".$_POST['image_id']."' LIMIT 1");
            $result2 = mysql_query($query);
            header("Location: index.php?page=selfies");
        }