如何通过按钮传值到Bootstrap模态框,仅用PHP更新MySQL用户表数据
Solution to Display and Edit MySQL User Data with Bootstrap Modal (PHP-only Update)
Hey there! Let's walk through how to implement your requirements step by step. I'll provide complete, working code with explanations.
1. Full User Table & Modal Page (index.php)
This page will display your user table, handle the Bootstrap modal trigger, and populate the form with row data when the edit button is clicked.
<!DOCTYPE html> <html> <head> <title>User Management</title> <!-- Bootstrap CSS for styling --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container mt-5"> <h2>User List</h2> <table class="table table-hover"> <thead> <tr> <th>Name</th> <th>Gender</th> <th>Age</th> <th>Action</th> </tr> </thead> <tbody> <?php require_once('dbconfig/config.php'); // Fetch all users from the database $result = mysqli_query($con, "SELECT * FROM user"); while ($row = mysqli_fetch_assoc($result)) { ?> <tr> <!-- Escape output to prevent XSS attacks --> <td><?php echo htmlspecialchars($row['name']); ?></td> <td><?php echo htmlspecialchars($row['gender']); ?></td> <td><?php echo htmlspecialchars($row['age']); ?></td> <td> <!-- Edit button with data attributes to store user info --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editModal" data-id="<?php echo $row['id']; ?>" data-name="<?php echo htmlspecialchars($row['name']); ?>" data-gender="<?php echo htmlspecialchars($row['gender']); ?>" data-age="<?php echo $row['age']; ?>"> Edit </button> </td> </tr> <?php } ?> </tbody> </table> </div> <!-- Bootstrap Edit Modal --> <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="editModalLabel">Edit User</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <!-- Form submits to update script --> <form action="update_user.php" method="POST"> <div class="modal-body"> <!-- Hidden input to store user ID for update --> <input type="hidden" name="user_id" id="user_id"> <div class="mb-3"> <label for="name" class="form-label">Name</label> <input type="text" class="form-control" id="name" name="name" required> </div> <div class="mb-3"> <label for="gender" class="form-label">Gender</label> <input type="text" class="form-control" id="gender" name="gender" required> </div> <div class="mb-3"> <label for="age" class="form-label">Age</label> <input type="number" class="form-control" id="age" name="age" required> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save Changes</button> </div> </form> </div> </div> </div> <!-- Bootstrap JS for modal functionality --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script> // Populate modal form when edit button is clicked const editModal = document.getElementById('editModal'); editModal.addEventListener('show.bs.modal', (event) => { const button = event.relatedTarget; // The edit button that triggered the modal // Extract user data from button attributes const userId = button.getAttribute('data-id'); const userName = button.getAttribute('data-name'); const userGender = button.getAttribute('data-gender'); const userAge = button.getAttribute('data-age'); // Fill modal form fields editModal.querySelector('#user_id').value = userId; editModal.querySelector('#name').value = userName; editModal.querySelector('#gender').value = userGender; editModal.querySelector('#age').value = userAge; }); </script> </body> </html>
2. PHP Update Handler (update_user.php)
This file handles the form submission, updates the MySQL database, and redirects back to the user list.
<?php require_once('dbconfig/config.php'); // Only process POST requests if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Sanitize input to prevent SQL injection $user_id = mysqli_real_escape_string($con, $_POST['user_id']); $name = mysqli_real_escape_string($con, $_POST['name']); $gender = mysqli_real_escape_string($con, $_POST['gender']); $age = mysqli_real_escape_string($con, $_POST['age']); // Update query $updateQuery = "UPDATE user SET name = '$name', gender = '$gender', age = '$age' WHERE id = '$user_id'"; if (mysqli_query($con, $updateQuery)) { // Redirect back to user list after successful update header("Location: index.php"); exit(); } else { echo "Error updating user: " . mysqli_error($con); } } ?>
Key Details to Note:
- Security: We use
htmlspecialchars()when outputting user data to prevent XSS attacks, andmysqli_real_escape_string()to sanitize input before inserting into MySQL (to avoid SQL injection). - Modal Populating: The JavaScript part is necessary to dynamically fill the modal with the correct user data when the edit button is clicked—this is standard for Bootstrap modals, and the actual data update is handled purely with PHP as you requested.
- Database Connection: Ensure your
dbconfig/config.phpfile has the correct connection details (example below):<?php $con = mysqli_connect("localhost", "your_username", "your_password", "your_database"); if (!$con) { die("Connection failed: " . mysqli_connect_error()); } ?>
内容的提问来源于stack exchange,提问作者satya dasari
相关产品推荐
相关产品推荐

