首页 > 解决方案 > 我必须从数据库输出我的数据,还必须从表单中复制所有输入以将它们发送给我自己,包括实时乘法 weight*pcs

问题描述

我有一些代码,我必须从客户端输入我的联系人数据,并 从 MySQL 数据库输出数据,这会在表中创建新行

还有必须在代码中的附加功能 - 但我不知道如何处理这个问题。我必须实时计算元素件的数量 x 它们的重量,以向客户显示订单的总重量。

问题是我不知道如何让客户在更改Pieces中的值时看到它<input>

最后,表格和表格中的数据必须通过电子邮件发送给员工。

PHP代码:

 <html>
  <head>
    <meta charset="utf-8" />
    <meta name="calculator" content="width=device-width, initial-scale=1"/>
        <title>Test</title>
        <link rel="stylesheet" href="style.css" >
  </head>

    <body>
        <!-- including calc.php file which contains all variables -->
        <?php include 'calc.php'; ?>
        <!-- Printing the form -->
    <form method="post" action="sendform.php"><br>
    
     <center>
     <h1>TEST</h1>
        <input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
         <input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
          <input id="Email" type="email" placeholder="<?= $form['EMAIL']; ?>" class="form-contact" required><br>
           <input id="Country" type="text" placeholder="<?= $form['COUNTRY']; ?>" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
            <input id="Phone" type="text" placeholder="<?= $form['PHONE']; ?>" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
            <br>
            
        <!-- Printing out the table -->
        
  <table class="table-responsive" border="1">
    <thead>
        <tr>
            <th><?= $form['PRODUCTS']; ?></th>
            <th><?= $form['CATALOG']; ?></th>
            <th><?= $form['DESC']; ?></th>
            <th><?= $form['WEIGHT']; ?></th>
            <th><?= $form['TWEIGHT']; ?></th>
        <br>
        </tr>

    </thead>
      <tbody>
      
      <?php
            # Database connection
                $dbhost = "localhost";
                $dbuser = "root";
                $dbpass = "1234";
                $dbname = "data";

                $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
                if ($connection->connect_error) {
                    die("Connection failed: " . $connection->connect_error);
                }
                #echo "Connection successfull!";
                
                # Questions for Database
                $sql = 'SELECT * FROM `elements`';
                $result = mysqli_query($connection, $sql);
                
                    if (mysqli_num_rows($result) > 0) {
                        //output data each row
                        while($row = mysqli_fetch_assoc($result)) {
                            echo "<tr><td>".'<input class="pcs-input" min=0 maxlength="3" value=0 size="2px" style="background-color: white;" name="inputs[]">';
                            echo "</td><td>Nr. "  . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sumWeight'></div></td></tr>";
                            
                        }
                        } else {
                        echo "0 Results";
                    }

                mysqli_close($connection);
      ?>

      </tbody>
    </table>
        <!-- Counting all needed atributes -->
            <div id="totalWeight">totalWeight</div>
        <!-- Submit btn -->
        <br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
        </center>
    </form>
        
    </body>
    
  </html>

JavaScript 代码

    <script type="text/javascript">
    document.addEventListener(function()
    input.OnChange = calculateForm();
    function calculateForm() {
        var totalWeight = 0;
        $(".pcs-input").each(function () {
            var pcs = parseInt($(this).val());
            if (pcs < 0) {
                pcs = 0;
            } else {
                var weight = parseFloat($(this).data('weight'));
                var sumWeight = pcs * weight;
                totalWeight += sumWeight;
            }
        });
       document.write(totalWeight.toFixed(2) + ' kg');
      }
    )};
    </script>

更新

好吧,它不再起作用,没有错误,只是没有成倍增加 我认为问题可能在于将数据从表/数据库传输到变量中,有什么解决方案吗?

 <?php
            # Database connection
                $dbhost = "localhost";
                $dbuser = "root";
                $dbpass = "1234";
                $dbname = "data";

                $connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
                if ($connection->connect_error) {
                    die("Connection failed: " . $connection->connect_error);
                }
                #echo "Connection successfull!";
                
                # Questions for Database
                $sql = 'SELECT * FROM `elements`';
                $result = mysqli_query($connection, $sql);
                
                    if (mysqli_num_rows($result) > 0) {
                        //output data each row
                        while($row = mysqli_fetch_assoc($result)) {
                            echo "<tr><td>"."<input type='number' class='pcs-input' id='inputs' data-weight=".$row["weight"];
                            echo "></input>";
                            # echo "<tr><td>".$row["id"].'';
                            echo "</td><td>Nr. "  . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sum-Weight2'></div></td></tr>";
                            
                        }
                      } else {
                        echo "0 Results";
                    }
        #Declaring JavaScript Code inside PHP
                mysqli_close($connection);
      ?>

      </tbody>
    </table>
    <script type="text/javascript">
    function calculateForm() {
        var totalWeight = 0;
        $(".pcs-input").each(function () {
            var pcs = parseInt($(this).val());
            if (pcs < 0) {
                pcs = 0;
            } else {
                var weight = parseFloat($(this).data('weight'));
                var sumWeight = pcs * weight;
                $(this).parent().parent().find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
                totalWeight += sumWeight;
            };
       $('.totalGewicht').html(totalWeight.toFixed(2) + ' kg');
      }
    )};
    </script>
        <!-- Counting all needed atributes -->
            <div id="totalWeight"></div>
        <!-- Submit btn -->
        <br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
        </center>
    </form>

标签: javascriptphphtml

解决方案


总体而言,您的代码存在很多问题,可以概括为

  • 无效的 HTML(例如重复的 ID、错误书写input的元素、未关闭的表格行、未关闭的数据属性)
  • 过于复杂的 HTML
  • 输入或大小写错误(例如W,代替w
  • JavaScript 中不正确的 CSS 选择器
  • 缺少初始默认数据(例如,如果任何一个输入框中没有数字,则计算将失败,因为尝试将空白值添加到另一个数字会导致NaN(非数字)
  • 页面加载时计算未运行,因此在用户更改某些内容之前数据丢失(如果他们想在更改任何值之前查看当前权重,这是没有用的)

这个客户端演示演示了生成 PHP 所需的 HTML,以及正确的 JavaScript / jQuery 代码,以便进行计算并显示结果:

$(function() {
  $(".pcs-input").change(calculateForm); //set up the event handler

  function calculateForm() {
    var totalWeight = 0;
    
    $(".pcs-input").each(function() {
      var pcs = parseInt($(this).val());
      
      if (pcs < 0) {
        pcs = 0;
      } 
      else {
        var weight = parseFloat($(this).data('weight'));
        var sumWeight = pcs * weight;
        $(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
        totalWeight += sumWeight;
      };
      $('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
    })
  };
  
  calculateForm(); //call it once when the page first loads too, to set up the initial data
});
table
{
  border-collapse:collapse;
}

td
{
  border: solid 1px black;
  padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td><input type='number' class='pcs-input' data-weight='3' value='1' /></td>
      <td>Nr. 14536</td>
      <td>Test 1</td>
      <td>3 kg</td>
      <td class='sum-weight2'></td>
    </tr>
    <tr>
      <td><input type='number' class='pcs-input' data-weight='15' value='1' /></td>
      <td>Nr. 23431</td>
      <td>Test 2</td>
      <td>15 kg</td>
      <td class='sum-weight2'></td>
    </tr>
    <tr>
      <td><input type='number' class='pcs-input' data-weight='4' value='1' /></td>
      <td>Nr. 33125</td>
      <td>Test 3</td>
      <td>4 kg</td>
      <td class='sum-weight2'></td>
    </tr>
  </tbody>
</table>
Total Weight: <span id="totalWeight"></span>

请记住,在“更改”事件触发之前,您需要将焦点从文本框移动到另一个元素(使用鼠标或 Tab 键)。(如果您使用输入框上的向上/向下按钮,它也会运行。)

所以这意味着,除了像我展示的那样编辑 JavaScript 之外,您还需要更改 PHP,以便它输出带有我上面演示的结构和数据的 HTML 表格行。

这应该有效:

while($row = mysqli_fetch_assoc($result)) {
  echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='1' /></td>";
  echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}

推荐阅读