简体   繁体   English

PHP使用mysql需要计算所有下拉框的总成本

[英]PHP using mysql need to calculate the total cost of all dropdown boxes

So I have multiple dropdown boxes and they have a price inside the drop down box and I want to gather all the prices of each dropdown box and echo it as a total price. 因此,我有多个下拉框,并且它们在下拉框内有一个价格,我想收集每个下拉框的所有价格并将其作为总价进行回显。 So far I have managed to echo the price but it's only displaying the last product of each dropdown box so it doesn't change price when the user selects different products. 到目前为止,我设法回显了价格,但是它仅显示每个下拉框的最后一个产品,因此当用户选择其他产品时,它不会更改价格。

        <?php
      //PSU QUERY
  $sqlpsu="SELECT id, psu, price, psuWATT FROM  PSU";
  $result = mysql_query($sqlpsu);

    echo "<select name='psu'>";
    while ($row = mysql_fetch_array($result)) {

        echo '<option value="'.$row["id"].'">'.$row["psu"]. " £" .$row["price"].'</option>';
        $pricePsu = $row["price"];
    }
    echo "</select>";
    ?>

before while set 在设置之前

$pricePsu = 0;

in the while use 在使用中

$pricePsu += $row["price"];

After while echo "$pricePsu" 经过一会儿echo "$pricePsu"

Option html 选项html

<select name="psu" id="psu" multiple="multiple">
  <option value="1" price="5">option1 $5</option>
  <option value="2" price="10">option2 $10</option>
  <option value="3" price="15">option3 $15</option>
</select>
<div></div>

Option javascript 选项javascript

$( "select" )
  .change(function() {
    var total = 0;
    var str = "";
    $( "#psu option:selected" ).each(function() {
      total += parseInt($( this ).attr("price")) ;
    });
    $( "div" ).text( total );
  })
  .trigger( "change" );

Example! 例! https://jsfiddle.net/Cuchu/epxvhfyh/ https://jsfiddle.net/Cuchu/epxvhfyh/

Good practice: 良好做法:

echo "<option value='{$row['id']}' price='{$row['price']}'>{$row['psu']} £ {$row['price']}</option>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM