English 中文(简体)
在一个多维数组中从 HTML 获取值, 使用 PHP 计算值
原标题:Get values from HTML in a multidimensional array and calculate values using PHP
  • 时间:2012-05-24 21:46:15
  •  标签:
  • php
  • arrays

我搜寻过,但无法解决这个问题。

我正在研究一个应用程序,该应用程序将产生数量不详的项目,并使用户从每个项目的下降量中选择数量。

Item(s) | price | Select qty
Rice     23      3
Beans    22      4
Eggs     52      5

...
...
...
unknown

请, 我如何用一个数组来捕捉上述内容, 并计算所有选定项目的总价值及相应的费用?

我有以下 HTML 代码 :

<form id= form1  name= form1  method= post  action= item_calc.php >
<?php
    .....
while($t_row = mysql_fetch_assoc($get_items)) {

echo "<p><label>$t_row[ $item_name ]
<input type= text  READONLY name= item_price[]  value= $t_row[ $item_price ]  /></label>
<input type= text  READONLY name= item_fees[]  value= $t_row[ $item_fee ]  /> 
<select name="item_qty">
<option value="1">
<option value="2">
<option value="3">
<option value="4">
<option value="5">
</select>
</p><p>";

}

        echo "<label><input type= submit  name= submit   value= Submit  /></label></p>
         </form>";

请, 我如何获得所有选定项目的项目_ 价格 + 项目_ feees * 项目_ qty?

这就是我尝试过的:

for ($i = 0; $i < count($_POST[ item_price ]); $i++) {
   // Do something here with $_POST[ checkbx ][$i]



   foreach ($_POST[ item_fees ] as $tkey => $tvalue) {
    //echo "Key: $tkey; Value: $tvalue<br>";
   }


   foreach ($_POST[ item_price ] as $pkey => $pvalue) {
    //echo "Key: $pkey; Value: $pvalue<br>";
   }

   $total = $tvalue + $pvalue;


}
echo $total;
最佳回答

I recommend to not put fees and prices into the form and read it out off the POST request. Some people do bad stuff like html injections or post parameter manipulation. You make them able to send you a request with their own prices and fees using manipulated POST parameters.

最简单的方法就是用火药打开您的页面, 用火虫来操纵价格和收费的值, 然后按下提交 - 即使输入只读!!!!

我的小费 - 做一些诸如:

<select name="quantity[unique-id]">
  <option value="null">choose...</option>
  ...your options...
</select>

其中独有的ID是每种产品的独特识别码,如数据库id。

然后在 php 中

foreach ($_POST[ quantity ] as $uniqueId => $quantity) {
  //... don t forget to check $uniqueId and $quantity for injections (like sql injections)
  //skip the products with no numeric quantity value
  if (!is_int($quantity) || $quantity < 1) {
    continue;
  }
  $fee = getFeeFor($uniqueId); // from database?
  $price = getPriceFor($uniqueId); // from database?
  //... do what you want: $price + $fee * $quantity
}

我希望这能帮到你

问题回答
  1. First of all, don t include single quotes in a double quote string when you re referencing arrays, you risk to have an "encapsed string" error.
  2. You also include a double quoted string in "item_qty" which will likely result in an error.
  3. Close the option tags with /> as best practice.
  4. Your LABEL tag is not used properly. The correct syntax is: <label for= html_element_id >My pretty label</label> <input id= html_element_id ... (my form control) ... /> and it s pretty useless (though always more semantic and structured) with other controls than checkboxes or radios.
  5. You may cosider using a TABLE instead of P tags to have everything lined up. Better, you could use CSS to line up things, much better practice.
  6. If you hard-code the choices it can be difficult to handle requirement changes: what if you need quantities from 1 to 10? What if you choose to use a textbox instead of a SELECT?

    while($t_row = mysql_fetch_assoc($get_items)) 
    {
        // Generate quantity string - can change the $qty string
        // for any imput method you like
    
        $qtyName = "item_qty[]";
    
        $qty = "<select name= " . $qtyName . " >";
        for ($i=1; $i<6; $i++)
        {
            // close the option tag as best practice!
            $qty .= "<option value= " . $i . "  />";
        }
        $qty .= "</select>";
    
        echo sprintf("<p>%s
        <input type= text  READONLY name= item_price[]  value= %s  /></label>
        <input type= text  READONLY name= item_fees[]  value= $s  /> " . $qty . "</p>",
        $t_row[ item_price ],
        $t_tow[ item_fee ]);
    }
    

收集数据很简单:

$sum = 0;
$fees = $_POST[ item_fee ];
$qtys = $_POST[ item_qty ];
$prices = $_POST[ item_price ];
$total = count($prices);

for ($i = 0; $i<total; $i++)
{
    $item_fee = $fees[$i] + 0; // trick to filter only numerical values and avoid data tampering
    $item_price = $price[$i] + 0;
    $item_quantity = $qtys[$i] + 0;

    $item_total = $item_price + $item_fee * $item_quantity; 

    $sum += $item_total;

}

我也同意,以你的形式直接表示价格,无论如何都会导致数据被篡改,建议你对照数据库检查的用户给出了非常明智的建议。

$total = 0;
$fee = $_POST[ item_fee ];
$qty = $_POST[ item_qty ];

foreach($_POST[ item_price ] as $k => $price) {
    $total += $price + ($fee[$k] * $qty[$k];
}

不确定您是否想要全部 或每件物品的总数。

如果每项项目需要总额,则将 $总计 + $$ + (fee[k] * $qty[k]; 改为 $总计 = $ + (fee[k] * $qty[k]; 并删除第一行( $总计=0; )。

更改 更改为

我有一个"强力"的SIMPLES 解决方案。

第一次更改 改为

然后在您的 item_ calc.php 中写这个

$itemprice = $_POST["item_price"];//tested with array(10,35,21)
$itemfees = $_POST["item_fees"];//tested with array(3,7,4)
$itemqty = $_POST["item_qty"];//tested with array(2,5,3)
$i = 0;
$total = 0;
foreach($itemprice as $price){
  $feesx = $itemfees[$i];
  $qtyx = $itemqty[$i];
  $calculated = ($price+$feesx)*$qtyx;
  $total = $total + $calculated;
  $i++;
}
echo $total;//echos 311 [{(10+3)*2}+{(37+7)*5}+{(21+4)*3}]

我测试过它,并且工作非常完美。 希望它能帮助 < code> :





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签