PHP总结文本框的值

时间:2014-11-04 11:35:47

标签: php textbox sum

如何总结文本框的值并显示它。例如,文本框的值为1和2,另一个文本框将显示3.请帮我解决问题。谢谢〜

  $name = $row['Name'];
  $data2 = mysql_query("SELECT * FROM tblstockmgt WHERE ItemName ='$name'") or die(mysql_error());
  while($row2= mysql_fetch_array( $data2 )) 
  {
    echo "<td align='right'><input type='text' name='txt[]' value='".$row2['Price']."'/></td>";
  }

4 个答案:

答案 0 :(得分:2)

只需创建一个varabile $total并始终将其删除,然后在循环之后将值写入文本框:

$total = 0;
 while($row2= mysql_fetch_array( $data2 )) {
    echo "<td align='right'><input type='text' name='txt[]' value='".$row2['Price']."'/></td>";
    $total += $row2['Price'];
}
?>
</tr>
<tr>
    <td>Total: <input type="textbox" name="total" value="<?php echo $total; ?>" /></td>
</tr>
  • 避免进行sql注入,让我们在查询中转义字符串。

  • 使用mysqli或PDO代替mysql函数,因为不推荐使用mysql函数。

答案 1 :(得分:0)

 $total = 0;
 while($row2= mysql_fetch_array( $data2 )) 
 {
    echo "<td align='right'><input type='text' name='txt[]' value='".$row2['Price']."'/>   </td>";
    $total += $row2['Price'];
 }
 echo "<td align='right'><input type='text' name='txt[]' value='".$total."'/>   </td>";

答案 2 :(得分:0)

您可以在循环中使用jquery或变量。 循环php求和

$sum = 0;
 while($row2= mysql_fetch_array( $data2 )) 
      {
        echo "<td align='right'><input type='text' name='txt[]' value='".$row2['Price']."'/></td>";
        $sum += $row2['Price'];
 }
echo $sum;

Jquery版本

 <div class="section">
        while($row2= mysql_fetch_array( $data2 )) 
          {
            echo "<td align='right'><input type='text' name='txt[]' value='".$row2['Price']."'/></td>";
        }
        <div id="mysum"></div>
        </div>

        <script>
            $('.section').each(function(){
                  var totalPoints = 0;
                  $(this).find('input').each(function(i,n){
                    totalPoints += parseInt($(n).val(),10); 
                  });
                  alert(totalPoints);
                   $('#mysum').html(totalPoints);
                });
        </script>

PDO版本,请将您的脚本转换为弃用的mysql_fetch等示例

try {
    $name= mysql_real_escape_string($row['Name']);
    $db = new PDO('mysql:host=localhost;dbname=tablename', 'user', 'password');
    $stmt = $db->prepare('SELECT * FROM tblstockmgt WHERE ItemName:=this');
    $stmt->bindValue(':this', $name, PDO::PARAM_STR);
    $stmt->execute();
    $results = $stmt->fetchAll();
    $sum = 0;
    if ($stmt->rowCount() == 0) {
        echo "No data";
        die();
    }
    foreach ($results as $result) {
       echo "<td align='right'><input type='text' name='txt[]' value='".$result['Price']."'/></td>";
       $sum += $result['Price'];

    }
        echo $sum;
}
catch (PDOException $ex) {
    die($ex->getMessage());
}

答案 3 :(得分:0)

像这样使用

$sum=0;

while($row2= mysql_fetch_array( $data2 ))
          {
            $sum += $row2['Price'];
            echo "<td align='right'><input type='text' name='txt[]' value='".$sum."'/></td>";

          }