蓝极冰焰 2024-07-01 12:41 采纳率: 40.7%
浏览 4
已结题

PHP 关于增减表单行,多行提交数据异步更新数据库的问题

遇到一个新增数据行并提交更新数据库的问题,点击“确认”按钮无效,请大家帮我看看问题:
sz.php页面(表单提交)

<form id="myForm" action="set_match.php" method="post">
    <table>
    <tbody id="entries-tbody">
        <tr class="entry-row">
            <td>组别项目:</td><td style="text-align: left;">
                <div class="add-row">
                    <input type="hidden" class="mname" name="mname" value="<?php echo $selectedNames; ?>">
                    <input type="hidden" class="mstation" name="mstation" value="<?php echo $selectedStation; ?>">
                <div id="entry-container">
                    <div class="entry">
                    <input type="text" class="group" name="group[]" placeholder="请输入组别">
                    <input type="text" class="event" name="event[]" placeholder="请输入项目">
                    </div>
                </div>
                    <button type="button" class="add-btn">增加</button>
                </div>
            </td>
            </tr>
        </tbody>
    </table>
    <button type="button" id="queren">确认</button>
    <input type="reset" value="清除">
    </form>

javascript (在sz.php页面下的)


    <script>
        $(document).ready(function() {
            var entryCount = 0; // 追踪当前有多少个输入行
            $('.add-btn').on('click', function() {
                var newEntry = $('<tr>').addClass('entry-line');
                newEntry.append($('<td>').text('新增组别、项目行: '));
                newEntry.append($('<td>').addClass('text-left').append(
                    $('<input>').attr({type: 'text', class: 'group',name: 'group[]', placeholder: '请输入组别'}),
                    ' ',
                    $('<input>').attr({type: 'text', class: 'event',name: 'event[]', placeholder: '请输入项目'}),
                    ' ',
                    $('<button>').attr({type: 'button', class: 'remove-btn'}).text('减少').on('click', function() {
                        $(this).closest('tr').remove(); // 删除当前行
                    })
                ));

                // 添加到表格中
                $('#entries-tbody').append(newEntry);
                entryCount++; // 更新行数
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            $('#queren').on('click', function(e) {
                e.preventDefault();
                console.log('Click event triggered');

                var formData = {
                    name: $('.mname').val(),
                    station: $('.mstation').val(),
                    groups: [],
                    events: []
                };
                $('#entry-container .entry').each(function() {
                    formData.groups.push($(this).find('.group').val());
                    formData.events.push($(this).find('.event').val());
                });
                // 使用AJAX发送数据到服务器
                $.post('set.php', formData, function(response) {
                    console.log(response);
                    // 根据需要处理响应
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    console.error("AJAX 请求失败: " + textStatus, errorThrown);
                });
            });
        });
    </script>

下面是set.php页面的代码

<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once '../conn/ss.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $station = $_POST['station'];
    $groups = $_POST['group']; // 注意这将是一个数组
    $events = $_POST['event']; // 注意这也将是一个数组
    $status = "确认";

    $pdo->beginTransaction();

    $sql = "INSERT INTO ms (name, station, `group`, event, status, editer) VALUES (:name, :station, :group, :event, :status)";
    $stmt = $pdo->prepare($sql);

    // 先绑定不会变的参数
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':station', $station);
    $stmt->bindParam(':status', $status);

    // 遍历组别和项目数组
    foreach ($groups as $index => $group) {
        $event = $events[$index]; // 获取当前索引的事件

        // 绑定当前迭代的组别和项目
        $stmt->bindParam(':group', $group);
        $stmt->bindParam(':event', $event);

        // 执行插入操作
        if (!$stmt->execute()) {
            // 如果插入失败,回滚事务并输出错误信息
            $pdo->rollBack();
            echo "插入记录时出错: " . $stmt->errorInfo()[2];
            break; // 跳出循环,不再继续尝试插入
        }
    }

    // 如果循环成功完成,提交事务
    if ($pdo->inTransaction()) {
        $pdo->commit();
        echo "所有记录已成功添加。";
    }

} else {
    echo "请操作!";
}

?>

  • 写回答

6条回答 默认 最新

  • 叫兽-郭老师 新星创作者: Java技术领域 2024-07-01 12:42
    关注

    🕒下午好,题主!目前:🟢[在线]
    📢参考通义千问、由郭老师整理提供!
    📣今日诗号:疏影横斜,暗香浮动,低酌浅唱月明中。休去,休去,惊起一枕奇梦。

    你遇到的问题是,你在点击“确认”按钮时,只获取了 #entry-container .entry 下的表单数据,而新增的行并不在 #entry-container 元素内,所以无法获取到新增行的表单数据。

    解决方案:

    1. 修改 HTML 结构: 将新增行的 input 元素也放置在 #entry-container 元素内,这样就可以统一获取所有表单数据。

    2. 修改 JavaScript 代码:$('#queren').on('click', ...) 事件处理函数中,遍历所有 entry-row 元素,获取每个 entry-row 元素内的表单数据。

    以下是修改后的完整代码:

    sz.php:

    <!DOCTYPE html>
    <html>
    <head>
      <title>新增数据行</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    </head>
    <body>
    <form id="myForm" action="set_match.php" method="post">
      <table>
        <tbody id="entries-tbody">
        <tr class="entry-row">
          <td>组别项目:</td>
          <td style="text-align: left;">
            <div class="add-row">
              <input type="hidden" class="mname" name="mname" value="<?php echo $selectedNames; ?>">
              <input type="hidden" class="mstation" name="mstation" value="<?php echo $selectedStation; ?>">
              <div id="entry-container">
                <div class="entry">
                  <input type="text" class="group" name="group[]" placeholder="请输入组别">
                  <input type="text" class="event" name="event[]" placeholder="请输入项目">
                </div>
              </div>
              <button type="button" class="add-btn">增加</button>
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <button type="button" id="queren">确认</button>
      <input type="reset" value="清除">
    </form>
    <script>
      $(document).ready(function () {
        var entryCount = 0; // 追踪当前有多少个输入行
        $('.add-btn').on('click', function () {
          var newEntry = $('<tr>').addClass('entry-row');
          newEntry.append($('<td>').text('新增组别、项目行: '));
          newEntry.append($('<td>').addClass('text-left').append(
              $('<div>').addClass('entry').append(
                  $('<input>').attr({
                    type: 'text',
                    class: 'group',
                    name: 'group[]',
                    placeholder: '请输入组别'
                  }),
                  ' ',
                  $('<input>').attr({
                    type: 'text',
                    class: 'event',
                    name: 'event[]',
                    placeholder: '请输入项目'
                  })
              ),
              ' ',
              $('<button>').attr({type: 'button', class: 'remove-btn'}).text('减少').on('click', function () {
                $(this).closest('tr').remove(); // 删除当前行
              })
          ));
          // 添加到表格中
          $('#entries-tbody').append(newEntry);
          entryCount++; // 更新行数
        });
    
    
        $('#queren').on('click', function (e) {
          e.preventDefault();
          console.log('Click event triggered');
          var formData = {
            name: $('.mname').val(),
            station: $('.mstation').val(),
            groups: [],
            events: []
          };
    
          // 遍历所有 entry-row 元素,获取表单数据
          $('.entry-row').each(function () {
            formData.groups.push($(this).find('.group').val());
            formData.events.push($(this).find('.event').val());
          });
    
          // 使用AJAX发送数据到服务器
          $.post('set.php', formData, function (response) {
            console.log(response);
            // 根据需要处理响应
          }).fail(function (jqXHR, textStatus, errorThrown) {
            console.error("AJAX 请求失败: " + textStatus, errorThrown);
          });
        });
      });
    </script>
    </body>
    </html>
    

    set.php:

    <?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    require_once '../conn/ss.php';
    session_start();
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      $name = $_POST['name'];
      $station = $_POST['station'];
      $groups = $_POST['groups']; // 注意这将是一个数组
      $events = $_POST['events']; // 注意这也将是一个数组
      $status = "确认";
      $pdo->beginTransaction();
    
      try {
        $sql = "INSERT INTO ms (name, station, `group`, event, status, editer) VALUES (:name, :station, :group, :event, :status, :editer)";
        $stmt = $pdo->prepare($sql);
    
        // 循环插入数据
        for ($i = 0; $i < count($groups); $i++) {
          $stmt->execute([
            ':name' => $name,
            ':station' => $station,
            ':group' => $groups[$i],
            ':event' => $events[$i],
            ':status' => $status,
            ':editer' => $_SESSION['username'] // 假设你已经存储了用户名到session中
          ]);
        }
    
        $pdo->commit();
        echo "所有记录已成功添加。";
      } catch (PDOException $e) {
        $pdo->rollBack();
        echo "插入记录时出错: " . $e->getMessage();
      }
    
    } else {
      echo "请操作!";
    }
    ?>
    

    注意:

    • 以上代码仅供参考,你需要根据实际情况修改代码中的数据库连接信息、表单字段名等。
    • 在实际应用中,建议对用户输入进行校验,防止 SQL 注入攻击。
    • set.php 中,我添加了 editer 字段,用于记录编辑者信息,你需要根据实际情况修改数据库表结构和代码。
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 7月9日
  • 已采纳回答 7月1日
  • 创建了问题 7月1日