如何仅通过php通过按钮传递值以引导模态和更新mysql数据库中的值 [英] How to pass the value through button to bootstrap modal and update values in mysql database using only php

查看:40
本文介绍了如何仅通过php通过按钮传递值以引导模态和更新mysql数据库中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户表值在网页中显示,每行带有编辑按钮...我需要在单击编辑按钮时以输入形式显示模式(必须传递该行的所有值)以及该行的值...

user table values showing in webpage with edit button for each row...i need when i click the edit button it display the modal (must pass the all values of that row) with that row values in input form...

      <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');
         $result = mysqli_query($con,"SELECT * FROM users");
          while($row = mysqli_fetch_array($result))
          {
            ?>
          <tr>
            <td><?php echo $row['name']; ?></a></td>
            <td><?php echo $row['gender']; ?></td>
            <td><?php echo $row['age']; ?></td>
            <td><button name="action" type="submit" value="Edit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Edit</button>
          </td>
          </tr>
          <?php 
          }
            ?>
        </tbody>
       </table>

现在,当我单击模式中的更新按钮时,它将更新用户表中我们输入的值,或者使用编辑按钮值中的获取值来更新默认值....我在php中需要.[我需要完全一样在图片中显示] [1]

Now when i click update button in modal then it will update the values in user table what we have enter or else default values using the get value from edit button value....i need in php.[i need exactly like showing in image][1]

 <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Edit</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
            <form action="sample.php" method="post">
            <label>Name:</label>
            <input type="text" class="form-control" name="name" value="">
            <label>Gender:</label>
            <label><input type="radio" name="optradio">male</label>
            <label><input type="radio" name="optradio">female</label><br>
            <label>Age:</label>
            <input type="text" class="form-control" name="age" value="">
            <button name="action" type="submit" value="update" class="btn btn-primary">Update</button>
            </form>

        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
        </div>
        </div>
    </div>
  </div>


  [1]: https://i.stack.imgur.com/hqCmD.png

推荐答案

这将是我的解决方案.

工作原理:

  • 从db表中获取用户列表,并将其显示在引导表中.
  • 每个用户ID被保存为相应的 editButton 的值.
  • 单击 editButton 时-在显示模式之前-通过执行对用户的ajax请求,用户ID用于从 users 中获取用户的数据. get-user.php .请注意,这是正常的工作流程:仅使用与html表中的用户记录相对应的用户ID来从 users 中获取所有其他用户数据,并将这些值填充到模式控件中.将所有用户值从html表传递"到模式是不合适的.为什么?因为html表中的数据可以以其他方式格式化为db表 users 的真实数据.如果您然后将格式值从html表传递"到模态,则模态中的数据也将以其他方式设置格式,如db表 users 中的格式.而且,当您单击 updateButton 时,必须先将不同格式的数据取消格式化,然后再保存到用户中.不太好.
  • 如果未找到用户数据,或引发错误(自定义或失败),则仍显示模式,但会显示引导警报(类型为"danger")(在中).模态消息 div),并且禁用了模态的所有输入和 updateButton .请注意,当模式关闭时,例如,在关闭模式后,将重新启用禁用的控件,并删除所有引导警报.在它被隐藏之前.
  • 如果找到用户数据,则将其填充到模式控件中,并显示模式.
  • 您可以更改模态中的值,然后最后单击 updateButton .然后,执行对 update-user.php 的ajax请求,更新 users 表中的用户值.
  • 如果可以成功更新用户,则模式中将显示成功"引导警报.否则,如果出现(自定义)错误,则会显示危险"警报.
  • The users list is fetched from the db table and displayed in a bootstrap table.
  • Each user id is saved as the value of the corresponding editButton.
  • When an editButton is clicked - and before the modal is shown - the user id is used to fetch the data of the user from users by performing an ajax request to get-user.php. Note that this is the normal workflow: using only the user id - corresponding to a user record in the html table - to fetch all other user data from users and to fill that values in the modal controls. It would not be appropriate to "pass" all the user values from the html table to the modal. Why? Because the data in the html table can be formatted in other way as the real data of the db table users. If you would then "pass" the formatted values from the html table to the modal, your data in the modal would be also formatted in other way as in the db table users. And, when you would click on the updateButton, that different formatted data would have to be un-formatted before saving into users. Not so good.
  • If no user data is found, or errors are raised (custom, or on-failure), then the modal is still shown, but a bootstrap alert (of type "danger") is displayed (in the .modal-messages div) and all inputs and the updateButton of the modal are disabled. Note that the disabled controls are re-enabled and all bootstrap alerts are removed when the modal is closed, e.g. before it becomes hidden.
  • If user data is found, it is filled into the modal controls and the modal is shown.
  • One can change then the values in the modal and click on the updateButton in the end. Then, an ajax request to update-user.php is performed, updating the user values in the users table.
  • If the user could be successfully updated, a "success" bootstrap alert is shown in the modal. Otherwise, in case of (custom) errors, a "danger" alert is displayed.

代码结构:

该代码包含四个文件:

  • index.php :包含用户列表(例如引导表),由不同事件触发的模式和客户端功能.
  • get-user.php :包含用于通过其用户ID提取用户的php代码.
  • update-user.php :执行在其中更改的用户值的保存操作.模态的.
  • connection.php :包含错误报告功能和用于创建mysqli连接的代码.
  • index.php: contains the users list (e.g. the bootstrap table), the modal and the client-side functionality triggered by different events.
  • get-user.php: contains the php code for fetching a user by her/his user id.
  • update-user.php: performs the saving operation of the user values changed in the. modal.
  • connection.php: contains the error reporting functions and the code for creating the mysqli connection.

注释/建议:

  • 我的代码使用面向对象的mysqli扩展名.
  • 我总体上在以下方面实现了准备的语句为了避免任何SQL注入的可能性.对这些步骤进行了注释,以使其更加清楚和理解.
  • 如果需要,您可以阅读
  • My code uses the object-oriented mysqli extension.
  • I implemented prepared statements overall, in order to avoid any SQL injection possibility. The steps are commented for clarity and understanding.
  • If you want, you could read this and this article to see how to implement error/exception handling.

我对您可能遇到的任何问题持开放态度.所以,不要犹豫,问什么.

I am open to any question you may have. So, don't hesitate to ask anything.

<?php
require 'connection.php';

/*
 * The SQL statement to be prepared.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'SELECT * 
        FROM users';

/*
 * Prepare the SQL statement for execution - ONLY ONCE.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Execute the prepared SQL statement.
 * When executed any parameter markers which exist will 
 * automatically be replaced with the appropriate data.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.execute.php
 */
$statement->execute();

/*
 * Get the result set from the prepared statement.
 * 
 * NOTA BENE:
 * Available only with mysqlnd ("MySQL Native Driver")! If this 
 * is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in 
 * PHP config file (php.ini) and restart web server (I assume Apache) and 
 * mysql service. Or use the following functions instead:
 * mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.get-result.php
 * @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
 */
$result = $statement->get_result();

/*
 * Fetch data and save it into an array:
 * 
 *  Array (
 *      [0] => Array (
 *          [id] => 1
 *      [name] => Sai
 *      [gender] => male
 *      [age] => 23
 *      )
 *  [1] => Array (
 *      [id] => 2
 *      [name] => Satya
 *          [gender] => female
 *      [age] => 18
 *  )
 *  )
 * 
 * @link http://php.net/manual/en/mysqli-result.fetch-all.php
 */
$users = $result->fetch_all(MYSQLI_ASSOC);

/*
 * Free the memory associated with the result. You should 
 * always free your result when it is not needed anymore.
 * 
 * @link http://php.net/manual/en/mysqli-result.free.php
 */
$result->close();

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.close.php
 */
$statement->close();

/*
 * Close the previously opened database connection.
 * 
 * @link http://php.net/manual/en/mysqli.close.php
 */
$connection->close();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet" />
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet">

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                /*
                 * Fill the modal with data on modal show.
                 */
                $('#editModal').on('show.bs.modal', function (event) {
                    var modal = $(this);

                    // Extract the user id from the modal triggering button.
                    var editButton = $(event.relatedTarget);
                    var userId = editButton.val();

                    // Set the user id in the modal (read prior to update operation).
                    modal.find('#userId').val(userId);

                    // Fetch the user details and update the modal's content with them.
                    $.ajax({
                        method: 'post',
                        dataType: 'json',
                        url: 'get-user.php',
                        data: {
                            'userId': userId
                        },
                        success: function (response, textStatus, jqXHR) {
                            modal.find('.modal-title').text('Edit user ' + response.id);
                            modal.find('#name').val(response.name);

                            switch (response.gender) {
                                case 'female':
                                    modal.find('#genderOptionFemale').prop('checked', true);
                                    break;
                                case 'male': // No break.
                                default:
                                    modal.find('#genderOptionMale').prop('checked', true);
                                    break;
                            }

                            modal.find('#age').val(response.age);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            /*
                             * If the status code of the response is a custom one, defined by 
                             * the developer - here 420, then the corresponding error message 
                             * is displayed. Otherwise, the displayed message will be a general 
                             * user-friendly one - so, that no system-related infos will be shown.
                             */
                            var message = (jqXHR.status === 420)
                                    ? jqXHR.statusText
                                    : 'An error occurred during your request. Please try again.';

                            displayModalAlert(modal, 'danger', message);
                            disableModalControls(modal);
                        },
                        complete: function (jqXHR, textStatus) {
                            //...
                        }
                    });
                });

                /*
                 * Re-enable the disabled controls on modal hide.
                 */
                $('#editModal').on('hide.bs.modal', function (event) {
                    var modal = $(this);

                    removeModalAlerts(modal);
                    enableModalControls(modal);
                });

                /*
                 * Update the user with the user input values.
                 */
                $('#updateButton').on('click', function (event) {
                    var modal = $('#editModal');

                    removeModalAlerts(modal);

                    $.ajax({
                        method: 'post',
                        dataType: 'json',
                        url: 'update-user.php',
                        data: {
                            'userId': modal.find('#userId').val(),
                            'name': modal.find('#name').val(),
                            'gender': modal.find('input[name="genderOptions"]:checked').val(),
                            'age': modal.find('#age').val()
                        },
                        success: function (response, textStatus, jqXHR) {
                            displayModalAlert(modal, 'success', response);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            /*
                             * If the status code of the response is a custom one, defined by 
                             * the developer - here 420, then the corresponding error message 
                             * is displayed. Otherwise, the displayed message will be a general 
                             * user-friendly one - so, that no system-related infos will be shown.
                             */
                            var message = (jqXHR.status === 420)
                                    ? jqXHR.statusText
                                    : 'An error occurred during your request. Please try again.';

                            displayModalAlert(modal, 'danger', message);
                        },
                        complete: function (jqXHR, textStatus) {
                            //...
                        }
                    });
                });
            });

            /**
             * Display a bootstrap alert in the modal.
             * 
             * @param modal object The modal object.
             * @param type string Type of alert (success|info|warning|danger).
             * @param message string Alert message.
             * @return void
             */
            function displayModalAlert(modal, type, message) {
                modal.find('.modal-messages').html(getAlert(type, message));
            }

            /**
             * Remove any bootstrap alert from the modal.
             * 
             * @param modal object The modal object.
             * @return void
             */
            function removeModalAlerts(modal) {
                modal.find('.modal-messages').html('');
            }

            /**
             * Disable predefined modal controls.
             * 
             * @param modal object The modal object.
             * @return void
             */
            function disableModalControls(modal) {
                modal.find('.disabled-on-error')
                        .prop('disabled', true)
                        .addClass('disabled')
                        .css({
                            'cursor': 'not-allowed'
                        });
            }

            /**
             * Enable predefined modal controls.
             * 
             * @param modal object The modal object.
             * @return void
             */
            function enableModalControls(modal) {
                modal.find('.disabled-on-error')
                        .prop('disabled', false)
                        .removeClass('disabled')
                        .css({
                            'cursor': 'auto'
                        });
            }

            /**
             * Get a bootstrap alert.
             * 
             * @param type string Type of alert (success|info|warning|danger).
             * @param message string Alert message.
             * @return string The bootstrap alert.
             */
            function getAlert(type, message) {
                return '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">'
                        + '<span>' + message + '</span>'
                        + '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
                        + '<span aria-hidden="true">&times;</span>'
                        + '</button>'
                        + '</div>';
            }
        </script>

        <style type="text/css">
            body {
                margin: 0;
                padding: 20px;
            }
        </style>
    </head>
    <body>

        <div class="container">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Gender</th>
                        <th>Age</th>
                        <th>&nbsp;</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($users) {
                        foreach ($users as $user) {
                            $id = $user['id'];
                            $name = $user['name'];
                            $gender = $user['gender'];
                            $age = $user['age'];
                            ?>
                            <tr>
                                <td>
                                    <?php echo $name; ?>
                                </td>
                                <td>
                                    <?php echo $gender; ?>
                                </td>
                                <td>
                                    <?php echo $age; ?>
                                </td>
                                <td>
                                    <button type="button" id="editButton" name="editButton" value="<?php echo $id; ?>" class="btn btn-primary" data-toggle="modal" data-target="#editModal">
                                        Edit
                                    </button>
                                </td>
                            </tr>
                            <?php
                        }
                    } else {
                        ?>
                        <tr>
                            <td colspan="4">
                                - No users found -
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">

                    <div class="modal-header">
                        <h5 class="modal-title" id="editModalLabel">Edit</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>

                    <div class="modal-body">
                        <div class="modal-messages"></div>

                        <form>
                            <input type="hidden" id="userId" name="userId">

                            <div class="form-group">
                                <label for="name">Name *</label>
                                <input type="text" id="name" name="name" class="form-control disabled-on-error">
                            </div>

                            <div class="form-group">
                                <label>Gender</label>
                                <div class="form-check form-check-inline">
                                    <input type="radio" id="genderOptionMale" name="genderOptions" value="male" class="form-check-input disabled-on-error">
                                    <label for="genderOptionMale" class="form-check-label">male</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input type="radio" id="genderOptionFemale" name="genderOptions" value="female" class="form-check-input disabled-on-error">
                                    <label for="genderOptionFemale" class="form-check-label">female</label>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="age">Age</label>
                                <input type="number" id="age" name="age" class="form-control disabled-on-error">
                            </div>

                            <small class="form-text text-muted">* - Mandatory fields</small>
                        </form>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" id="updateButton" name="updateButton" value="update" class="btn btn-primary disabled-on-error">
                            Update
                        </button>
                    </div>
                </div>
            </div>
        </div>

    </body>
</html>

get-user.php

<?php

require 'connection.php';

// Validate the posted user id.
if (!isset($_POST['userId']) || empty($_POST['userId'])) {
    /*
     * This custom response header triggers the ajax error because the status 
     * code begins with 4xx (which corresponds to the client errors). Here is
     * defined "420" as the custom status code. One can choose whatever code 
     * between 401-499 which is not officially assigned, e.g. which is marked 
     * as "Unassigned" in the official HTTP Status Code Registry. See the link.
     * 
     * @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
     */
    header('HTTP/1.1 420 No user specified.');
    exit();
} /* Other validations here using elseif statements */

// Get the user id.
$userId = $_POST['userId'];

/*
 * The SQL statement to be prepared. Notice the so-called markers, 
 * e.g. the "?" signs. They will be replaced later with the 
 * corresponding values when using mysqli_stmt::bind_param.
 * 
 * @link http://php.net/manual/en/mysqli.prepare.php
 */
$sql = 'SELECT * 
        FROM users
        WHERE id = ?
        LIMIT 1';

$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$statement->bind_param('i', $userId);

$statement->execute();
$result = $statement->get_result();

/*
 * Fetch data and save it into an array:
 * 
 *  Array (
 *      [id] => 1
 *  [name] => Sai
 *  [gender] => male
 *  [age] => 23
 *  )
 * 
 * @link https://secure.php.net/manual/en/mysqli-result.fetch-array.php
 */
$user = $result->fetch_array(MYSQLI_ASSOC);

/*
 * When no records are found, fetch_array() 
 * returns NULL. In this case throw an error.
 */
if (!isset($user)) {
    header('HTTP/1.1 420 No user found by the given criteria.');
    exit();
}

$result->close();
$statement->close();
$connection->close();

echo json_encode($user);
exit();

update-user.php

<?php

require 'connection.php';

// Validate the posted user id.
if (!isset($_POST['userId']) || empty($_POST['userId'])) {
    header('HTTP/1.1 420 No user specified.');
    exit();
} /* Other validations here using elseif statements */

// Validate the posted user name.
if (!isset($_POST['name']) || empty($_POST['name'])) {
    header('HTTP/1.1 420 Please provide the name.');
    exit();
} /* Other validations here using elseif statements */

// Get the posted values.
$userId = $_POST['userId'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$age = $_POST['age'];

$sql = 'UPDATE users 
        SET 
            id = ?,
            name = ?,
            gender = ?,
            age = ? 
        WHERE id = ?';

$statement = $connection->prepare($sql);

$statement->bind_param('issii', $userId, $name, $gender, $age, $userId);

$statement->execute();

$affectedRows = $connection->affected_rows;

$statement->close();
$connection->close();

if ($affectedRows === -1) {
    header('HTTP/1.1 420 An error occurred during your request. Please try again.');
    exit();
} else {
    echo json_encode('User data successfully saved.');
    exit();
}

connection.php

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/*
 * Error reporting.
 * 
 * Also, define an error handler, an exception handler and, eventually, 
 * a shutdown handler function to handle the raised errors and exceptions.
 * 
 * @link https://phpdelusions.net/articles/error_reporting Error reporting basics
 * @link http://php.net/manual/en/function.error-reporting.php
 * @link http://php.net/manual/en/function.set-error-handler.php
 * @link http://php.net/manual/en/function.set-exception-handler.php
 * @link http://php.net/manual/en/function.register-shutdown-function.php
 */
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception).
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Create a new db connection.
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

创建表语法

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `gender` enum('male','female') NOT NULL DEFAULT 'male',
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这篇关于如何仅通过php通过按钮传递值以引导模态和更新mysql数据库中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆