2012-02-22 192 views
2

我有一個表單選擇,允許用戶從動態生成的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> 

我希望把選定的單選價值爲每個「檢查」產品進入一個MySQL表

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

我知道我需要的for_each每個選定的產品,但我有麻煩搞清楚如何在for_each循環期間將整個$ POST中正確的單選按鈕與產品相關聯,以將值放入MySQL表中。

回答

1

可能有更優雅的做事方式,但這是我的解決方案。我用<label></label>標籤包裝了你的複選框和收音機,所以文本是可點擊的(也是一個很好的練習訪問指南)。每個產品都使用唯一的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 . '); '); 
    } 
} 
+0

這很好用!感謝您的幫助。 – user1226570 2012-02-23 22:24:05