正确获取和删除帖子

时间:2018-07-09 17:26:12

标签: php mysql mysqli

我可以寻求帮助吗?

Index.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>

Delete.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; ?>">

1 个答案:

答案 0 :(得分:0)

为按钮提供一个并使用$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'];