You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

后台仪表盘编辑数据库用户:模态框显示错误数据的解决方法

问题原因

你当前代码的核心问题是所有编辑按钮都绑定了同一个ID为exampleModal的弹窗,而HTML中ID是全局唯一标识,浏览器只会渲染第一个匹配该ID的元素,所以无论点击哪一行的编辑按钮,都会打开第一条用户对应的弹窗。

解决方案一:为每行生成唯一弹窗ID(简单直接)

给每个用户的弹窗生成唯一ID,确保按钮和对应弹窗一一绑定:

<?php
include_once '../dashboard/dashHeader.php';
?>
    
<section>
    <table class="table table-striped" style="border: 3px solid;">
        <thead>
            <tr>
                <th>UID</th>
                <th>Full Name</th>
                <th>Email</th>
                <th>User Name</th>
                <th>Role</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php
            include_once('../../includes/dbh.inc.php');
            $sql = "SELECT * FROM users ORDER by usersId";
            $result = mysqli_query($conn, $sql); 
            
            while($row = mysqli_fetch_array($result)){
                if ($row['type'] == 1) {
                    $role = "Admin";
                } else {
                    $role = "User";
                }
                // 生成唯一弹窗ID
                $modalId = "exampleModal-" . $row['usersId'];
                echo "<tr>";
                echo "<td>".$row['usersId']."</td>";
                echo "<td>".$row['usersName']."</td>";
                echo "<td>".$row['usersEmail']."</td>";
                echo "<td>".$row['usersUid']."</td>";
                echo "<td>".$role."</td>";
                echo '<td>
                        <button type="button" class="btn btn-link btn-sm btn-rounded" data-mdb-toggle="modal" data-mdb-target="#'.$modalId.'">
                        Edit
                        </button>

                        <!-- Modal -->
                        <div class="modal fade" id="'.$modalId.'" tabindex="-1" aria-labelledby="exampleModalLabel-'.$row['usersId'].'" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="exampleModalLabel-'.$row['usersId'].'">Editing: '.$row['usersUid'].'</h5>
                                    </div>
                                    <div class="modal-body">
                                        <!-- 填充用户数据到表单 -->
                                        <form action="update-user.inc.php" method="POST">
                                            <input type="hidden" name="userId" value="'.$row['usersId'].'">
                                            <div class="mb-3">
                                                <label for="fullName" class="form-label">Full Name</label>
                                                <input type="text" class="form-control" id="fullName" name="fullName" value="'.$row['usersName'].'">
                                            </div>
                                            <div class="mb-3">
                                                <label for="email" class="form-label">Email</label>
                                                <input type="email" class="form-control" id="email" name="email" value="'.$row['usersEmail'].'">
                                            </div>
                                            <div class="mb-3">
                                                <label for="userName" class="form-label">User Name</label>
                                                <input type="text" class="form-control" id="userName" name="userName" value="'.$row['usersUid'].'">
                                            </div>
                                            <div class="mb-3">
                                                <label for="role" class="form-label">Role</label>
                                                <select class="form-select" id="role" name="role">
                                                    <option value="0" '.($role == "User" ? "selected" : "").'>User</option>
                                                    <option value="1" '.($role == "Admin" ? "selected" : "").'>Admin</option>
                                                </select>
                                            </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button>
                                        <button type="submit" class="btn btn-primary">Save changes</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>';
                echo "</tr>";
            }
            ?>
        </tbody>
    </table>
</section>

<?php
include_once '../dashboard/dashFooter.php';
?>
解决方案二:复用单个弹窗(性能更优)

如果用户数量较多,生成大量弹窗会增加DOM体积,推荐复用单个弹窗,通过JavaScript动态填充数据:

<?php
include_once '../dashboard/dashHeader.php';
?>
    
<section>
    <table class="table table-striped" style="border: 3px solid;">
        <thead>
            <tr>
                <th>UID</th>
                <th>Full Name</th>
                <th>Email</th>
                <th>User Name</th>
                <th>Role</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php
            include_once('../../includes/dbh.inc.php');
            $sql = "SELECT * FROM users ORDER by usersId";
            $result = mysqli_query($conn, $sql); 
            
            while($row = mysqli_fetch_array($result)){
                if ($row['type'] == 1) {
                    $role = "Admin";
                } else {
                    $role = "User";
                }

                echo "<tr>";
                echo "<td>".$row['usersId']."</td>";
                echo "<td>".$row['usersName']."</td>";
                echo "<td>".$row['usersEmail']."</td>";
                echo "<td>".$row['usersUid']."</td>";
                echo "<td>".$role."</td>";
                // 给按钮添加自定义属性存储用户数据
                echo '<td>
                        <button type="button" class="btn btn-link btn-sm btn-rounded edit-btn" 
                                data-mdb-toggle="modal" data-mdb-target="#exampleModal"
                                data-user-id="'.$row['usersId'].'"
                                data-user-name="'.$row['usersName'].'"
                                data-user-email="'.$row['usersEmail'].'"
                                data-user-uid="'.$row['usersUid'].'"
                                data-user-role="'.$row['type'].'">
                        Edit
                        </button>
                    </td>';
                echo "</tr>";
            }
            ?>
        </tbody>
    </table>
</section>

<!-- 单个复用弹窗,放在循环外 -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Editing: <span id="modal-username"></span></h5>
            </div>
            <div class="modal-body">
                <form action="update-user.inc.php" method="POST">
                    <input type="hidden" name="userId" id="modal-user-id">
                    <div class="mb-3">
                        <label for="modal-fullname" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="modal-fullname" name="fullName">
                    </div>
                    <div class="mb-3">
                        <label for="modal-email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="modal-email" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="modal-uid" class="form-label">User Name</label>
                        <input type="text" class="form-control" id="modal-uid" name="userName">
                    </div>
                    <div class="mb-3">
                        <label for="modal-role" class="form-label">Role</label>
                        <select class="form-select" id="modal-role" name="role">
                            <option value="0">User</option>
                            <option value="1">Admin</option>
                        </select>
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// 监听编辑按钮点击,填充弹窗数据
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        // 从按钮属性获取数据
        const userId = this.getAttribute('data-user-id');
        const userName = this.getAttribute('data-user-name');
        const userEmail = this.getAttribute('data-user-email');
        const userUid = this.getAttribute('data-user-uid');
        const userRole = this.getAttribute('data-user-role');
        
        // 填充到弹窗表单
        document.getElementById('modal-user-id').value = userId;
        document.getElementById('modal-username').textContent = userUid;
        document.getElementById('modal-fullname').value = userName;
        document.getElementById('modal-email').value = userEmail;
        document.getElementById('modal-uid').value = userUid;
        document.getElementById('modal-role').value = userRole;
    });
});
</script>

<?php
include_once '../dashboard/dashFooter.php';
?>
后端更新逻辑(补充)

需要创建update-user.inc.php处理表单提交,示例代码:

<?php
include_once('../../includes/dbh.inc.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_POST['userId'];
    $fullName = $_POST['fullName'];
    $email = $_POST['email'];
    $userName = $_POST['userName'];
    $role = $_POST['role'];

    // 准备更新语句,防止SQL注入
    $stmt = $conn->prepare("UPDATE users SET usersName = ?, usersEmail = ?, usersUid = ?, type = ? WHERE usersId = ?");
    $stmt->bind_param("sssii", $fullName, $email, $userName, $role, $userId);
    
    if ($stmt->execute()) {
        // 更新成功,跳转回用户列表
        header("Location: your-dashboard-page.php");
        exit();
    } else {
        echo "更新失败:" . $stmt->error;
    }
    $stmt->close();
    $conn->close();
}
?>

内容的提问来源于stack exchange,提问作者HaydenRowleyYT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:51:54