【问题标题】:Multiple dynamic radio buttons based on checkbox selection基于复选框选择的多个动态单选按钮
【发布时间】:2012-03-13 03:50:45
【问题描述】:

我有一个表单选择,允许用户从动态生成的 MySQL 列表中选择产品,然后使用单选按钮对产品进行评分。

<input type="checkbox" value="$row[ProdID]" name="Product[]" id="Product$row[ProdID]" onclick="showhide_div($row[ProdID])" />$row[ProductName]

<div id="div$row[CatID]" style="display:none">
<input type="radio" name="ProductQual$row[ProdID]" id="PQ$row[ProdID]" value="1" /> Poor&nbsp;&nbsp;
<input type="radio" name="ProductQual$row[ProdID]" id="PQ$row[ProdID]" value="2" /> Fair&nbsp;&nbsp;
<input type="radio" name="ProductQual$row[ProdID]" id="PQ$row[ProdID]" value="3" /> Good&nbsp;&nbsp;
<input type="radio" name="ProductQual$row[ProdID]" id="PQ$row[ProdID]" value="4" /> Excellent&nbsp;&nbsp;
</div>

我想将每个“已检查”产品的选定单选值放入 M​​ySQL 表中

-----------------
| ProdID(a) | 3 |
| ProdID(b) | 1 |
-----------------

我知道我需要 for_each 每个选定的产品,但我无法弄清楚如何在 for_each 循环期间将正确的单选按钮从整个 $POST 关联到产品,以将值放入 M​​ySQL 表中。

【问题讨论】:

    标签: php mysql arrays forms radio-button


    【解决方案1】:

    可能有更优雅的做事方式,但这将是我的解决方案。我将您的复选框和收音机包裹在 &lt;label&gt;&lt;/label&gt; 标签中,因此文本是可点击的(也是一个很好的可访问性指南)。生成的 RADIO 带有每个产品的唯一 ID。

    <?php
    
    echo '<label><input type="checkbox" name="product_' . $row['ProdID'] . '" id="product_' . $row['ProdID'] . '" onclick="javascript:showhide_div(' . $row['ProdID'] . ')" /> ' . $row['ProductName'] . '</label>';
    
    echo <<<EOT
    <div id="div{$row['ProdID']}" style="display:none;">
    <label><input type="radio" name="productquality_{$row['ProdID']}" value="1" /> Poor</label>
    <label><input type="radio" name="productquality_{$row['ProdID']}" value="2" /> Fair</label>
    <label><input type="radio" name="productquality_{$row['ProdID']}" value="3" /> Good</label>
    <label><input type="radio" name="productquality_{$row['ProdID']}" value="4" /> Excellent</label>
    </div>
    EOT;
    

    在后端,所有评分字段都被解析并插入到一个表中。

    <?php
    
    foreach ( $_REQUEST as $k=>$v){   // Step through each _REQUEST (_POST or _GET) variable
    
        if ( strpos( $k, 'productquality' ) !== false ){    // Only parse productquality_X variables
            $parts = explode( '_', $k );    // Split at the underscore
            $id = $parts[1];    // ID is the part after the underscore
    
            // Do something, like insert into MySQL.  In reality best to escape the values, to make sure to prevent injection.
            mysql_query( ' INSERT INTO `quality` ( ProdID, Rating ) VALUES ( ' . $id . ', ' . $v . '); ');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-08
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多