首页 > 解决方案 > CRUD delete using modal form

问题描述

I am creating a CRUD using PHP extension with PDO, and I want to create a confirmation for registry deletion using Bootstrap modals, but I don't know how I can pass the ID information to the modal to delete, how can I do it?

index.php

<tbody>
                <?php
                $pdo = DB::connect();
                $stmt = $pdo->query("SELECT * FROM people");
                while ($row = $stmt->fetch()) {
                    echo "<tr>";
                    echo "<th scope='row'>" . $row["id"] . "</th>";
                    echo "<td>" . $row["first_name"] . "</td>";
                    echo "<td>" . $row["last_name"] . "</td>";
                    echo "<td>" . $row["notes"] . "</td>";
                    if ($row["allowed"]) {
                        echo "<td>" . "✔&quot; . "</td>";
                    } else {
                        echo "<td>" . "✗&quot; . "</td>";
                    };
                    echo "<td>";
                    // modal trigger
                    echo "<button type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Delete</button>";
                    echo "</td>";
                    echo "</tr>";
                }
                ?>
</tbody>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Do you want to delete this registry?</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-danger">Yes</button>
            </div>
        </div>
    </div>
</div>

标签: phppdobootstrap-modalcrud

解决方案


在此部分中添加您的 ID

echo "<button type='button' class='btn btn-danger' data-toggle='modal' data-target='#exampleModal' onclick='$(".delete_id").val('".$row["id"]."')'>Delete</button>";

然后在模态中添加一个隐藏的输入字段,如下所示:

<input type="hidden" name="delete_id" class="delete_id">

在此函数之前包含 jQuery。您还需要有一个删除文件来传递该变量。请求成功后,您可以重新呈现 HTML。

function deleteRecord() {
   var id = $(".delete_id").val();

    $.ajax({
    url:"/delete.php",
    method:"POST",
    data:{
      id: id,
    },
    success:function(response) {
    
   },
   });
} 

在我们存储了 ID 的值之后,我们可以删除它

<button type="submit" class="btn btn-danger" onclick="deleteRecord()">Yes</button>

希望这有帮助


推荐阅读