php - 正确获取和删除帖子

标签 php mysql mysqli

我能得到一些帮助吗?

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

最佳答案

给你的按钮一个并使用$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'];

关于php - 正确获取和删除帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51250999/

相关文章:

php - Yii 的无限滚动寻呼机扩展不显示寻呼机

php - Mysql PHP - 插入行后对表进行排序

php - SQL LIKE 查询失败 - 准备语句中的 fatal error

javascript - 是否可以让 MySQL 下的数据库将行导出到可通过 Web 访问的托管文件夹中?

php - 从表中删除特定值

javascript - 禁用提交,但首先提交表单

用于计算 html 表中值的平均值的 PHP 循环

javascript - 跨 html 文件访问 javascript 变量

javascript - 第二个元素没有在第一个元素的第一次调试中同时出现

php - Mysql限制删除检查