PHP, Submitting a two dimensional table with TextBox to proccess

删除回忆录丶 提交于 2019-12-13 08:04:57

问题


I am building an application which has a dynamic table, everytime you open the page table`s row and columns changes based on data in database. Each Row is a vendor company each colomn is a Item Title. All these vendors upply the same item, So this table has a textbox in each contains a TextBox so user can type the value, which represents the amount of fruit they want from that supplier. the following is the example.

So what I need to do now is, after entering these values, I'd like to process them through PHP, and then see 4 different reports at the confirm page, example: write the Company name and under that, what they have to supply for each item, then the next company, so on and so forth to the end.

I don't know if i should create different class for each textbox? or ID them!! SHould I Array them? I am confused.. If any of you guys can help, would be wonderful

Thanks a lot


回答1:


I would suggest you just name the input elements as an array. something like:

<input type="text" name="fruits[company1][apple]">
<input type="text" name="fruits[company1][berries]">
<input type="text" name="fruits[company1][orange]">
<input type="text" name="fruits[company1][bannana]">

<input type="text" name="fruits[company2][apple]">
<input type="text" name="fruits[company2][berries]">
<input type="text" name="fruits[company2][orange]">
<input type="text" name="fruits[company2][bannana]">

or the same thing with the fruit being the first level and company name being second. It is really the same thing and generally just as easy to use either one. Just depends on how you want to loop over the data once you post the form. You might be better off also using ids for the company name and/or the fruit. Just makes it so, for example, company names with a space are still valid.

Using the above form, you can process the data with something like this:

<?php
foreach($_POST['fruits'] as $company=>$row){
    foreach($row as $fruit=>$quantity){
        if(!is_numeric($quantity) || $quantity < 0){
            $quantity = 0;
        }
        echo "You selected {$quantity} {$fruit} from {$company}";
    }
}



回答2:


I would try creating a multi dim array with the ID of the item as the first dimension. Like this:

<input type="textbox" name="textbox[<?php echo $row['item_id']; ?>]["apple"]" value="<?php echo $row['apple']; ?>" />

Then, in your processing script:

foreach ($_POST['textbox'] as $row)
{
  foreach ($row as $key => $val)
  {
    $q = "update `items` set `apple` = {$val['apple']} where `item_id` = {$key}";
    mysql_query($q);
  }
}


来源:https://stackoverflow.com/questions/11907976/php-submitting-a-two-dimensional-table-with-textbox-to-proccess

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!