如何从用户输入和SQL数据库中的值创建计算字段

时间:2017-03-06 21:01:26

标签: javascript php html sql

我正在尝试添加一个计算字段,用户输入订单数量的数字并显示该产品的总成本

我有一个产品列表的表格,以及我的sql数据库中的详细信息

if ($num_results1 > 0) {
     echo "<table><tr><th>Row Number</th><th>Name</th><th>Quantity</th><th>Weight</th><th>Price</th><th>Total</th></tr>";

for ($i=0; $i <$num_results1; $i++)
{

$row = mysqli_fetch_assoc($result1);
echo
    "<tr>".
    "<td class = 'row-number'>". $i ."</td>".
    "<td class = 'Product-Name'>". $row["Cheese"]."</td>".
    "<td class = 'Quantity'>" .'<input type="number" name="Box" id="text" />'. "</td>".
    "<td class = 'Weight'>" . $row["Size(in Kg)"] ."kg". "</td>".
    "<td class = 'Cost'>" ."€ ". $row["SellingPrice(Euro)"]. "</td>".
    "<td class = 'total'>".'calculate('.$row["SellingPrice(Euro)"].')'."</input></td>".
    "</tr>";

calculate()是我正在编写的Javascript函数,用于按客户要订购的金额获得产品的成本

<script>
    function getQuantity(i)
    {
    //reference to the form
    var theForm =document.forms["customerOrder"];
    //referenece to the element
    var quantity = theForm.elements["Box"];
        var howmany=0;
    if(quantity[i].value!="")
    {
        howmany=parseInt(quantity[i].value);
    }
    return howmany;
    } 

    function calculate(k)
    {
    var calc= '.$row["SellingPrice(Euro)"].' * getQuantity(k);
    return calc;
    }
</script>

getQuantity()尝试拉取客户输入网页的值。

我试过用PHP代码中的echo调用脚本,我认为我的问题是尝试获取数量的参考

总而言之,我希望创建一个计算总成本的函数并显示在我的上一栏中,并且它需要是动态的,以适应我的sql数据库随着待售产品的数量的变化,谢谢

1 个答案:

答案 0 :(得分:0)

你不能像你那样继续前进。如果您有多行,则无法在单个javascript函数中传递PHP多个值。您可以在HTML标记中添加一些ID,以便能够检索字段。这是jsfiddle向您展示的示例。

所以在你的情况下你可以这样做:

if ($num_results1 > 0) {
    echo "<table><tr><th>Row Number</th><th>Name</th><th>Quantity</th><th>Weight</th><th>Price</th><th>Total</th></tr>";

    for ($i=0; $i <$num_results1; $i++)
    {

        $row = mysqli_fetch_assoc($result1);
        echo
        "<tr>".
        "<td class = 'row-number'>". $i ."</td>".
        "<td class = 'Product-Name'>". $row["Cheese"]."</td>".
        "<td class = 'Quantity'>" .'<input type="number" id="qty-'.$i.'" onchange="calculate('.$i.')" />'. "</td>".
        "<td class = 'Weight'>" . $row["Size(in Kg)"] ."kg". "</td>".
        "<td class = 'Cost'>€ <span id='qty-".$i."'>". $row["SellingPrice(Euro)"]. "</span></td>".
        "<td class = 'total' id='total-".$i."'></td>".
        "</tr>";
    }
}

和javascript:

<script>
    function calculate(lineNumber) {
            var quantity = parseInt(document.getElementById('qty-' + lineNumber).value);
            var cost = parseInt(document.getElementById('cost-' + lineNumber).innerHTML);

            document.getElementById('total-' + lineNumber).innerHTML = cost * quantity;
    }
</script>