正确获取和删除帖子

5f0d552i  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(227)

我能得到一些帮助吗?
索引.php:

<form class="delete" id="delete" action="../functions/delete.php" method="POST">

    <table class="table">

        <?php
        include('../../configs/dbconfig.php');

        $sql = "SELECT id, title FROM posts";
        $posts = $connection->query($sql);
        while($row = $posts->fetch_assoc()) {
            $id = $row["id"];
            $title = $row["title"];
            ?>

            <thead class="thead-light">
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Headline</th>
                    <th scole="col">Action</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th><?php echo $id; ?></th>
                    <td><?php echo $title; ?></td>
                    <td><button type="submit" id="btn-delete" name="submit" class="btn btn-light"><i class="fas fa-minus-circle"></i> Delete</button></td>
                </tr>
            </tbody>
        <?php } ?>
    </table>
</form>

删除.php:

<?php
include('../../configs/dbconfig.php');

$id = $_POST['id']; // Can I get some help?
$sql = "DELETE FROM posts WHERE id=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("i", $id);
if($stmt->execute()) {
    echo "deleted";
} else {
    echo "error";
}
?>

它生成每个帖子的id和标题,并且有一个按钮,单击它之后,它应该删除正确的id,但它总是删除最后一个,代码如下:

<input type="hidden" name="id" value="<?php echo $id; ?>">
mmvthczy

mmvthczy1#

给你的按钮一个值并使用 $id :

<td><button type="submit" name="submit" value="<?php echo $id; ?>" id="btn-delete" class="btn btn-light"><i class="fas fa-minus-circle"></i> Delete</button></td>

然后使用名称获取值:

$id = $_POST['submit'];

相关问题