2012-10-20 43 views
0

我遇到了一个问题...我有一对复选框,我已命名和编号。我需要将复选框标记并将它们插入到我的数据库中。这里是我如何创建复选框:从两个复选框获取值并插入到mysql

<div class="check"><input type="checkbox" name="acharge1" value="1"> <span style="color: #0C0">$$</span><input type="checkbox" name="amenities1" value="1">Amenity 1</div> 
<div class="check"><input type="checkbox" name="acharge2" value="1"> <span style="color: #0C0">$$</span><input type="checkbox" name="amenities2" value="1">Amenity 2</div> 
<div class="check"><input type="checkbox" name="acharge3" value="1"> <span style="color: #0C0">$$</span><input type="checkbox" name="amenities3" value="1">Amenity 3</div> 
<div class="check"><input type="checkbox" name="acharge4" value="1"> <span style="color: #0C0">$$</span><input type="checkbox" name="amenities4" value="1">Amenity 4</div> 

其中一些将被检查和一些不会。他们也不总是成对检查,​​但我必须成对上传到我的数据库。换句话说:acharge1和amenities1不会被检查,但acharge2和amenities2会被检测到。所以我尝试了一个foreach循环,但没有奏效。我也尝试了一段时间循环,但我不知道要检查什么。因此,这是我现在有:

$aa = 1; 
    echo "Amenity: ".$_POST['amenities'.$aa]; 
    $aa++; 
    while(isset($_POST['amenities'.$aa])){ 
     $amen = $_POST['amenities'.$aa]; 
     if(isset($_POST['acharge'.$aa])){ 
     $acharge = $_POST['acharge'.$aa]; 
     }else{ 
      $acharge = "0"; 
      } 
     echo "Amen: ". $amen." charge: ".$acharge; 
     mysql_query("INSERT INTO hotel_amenities (amenity_code, hotel_id, charge) VALUES ('$amen','$hotel_id','$acharge')") or die(mysql_error()); 
     echo $aa; 
     $aa++; 
     } 

但正如你所看到的这个是不行的,因为如果amenities1未选中它不会通过别人做while循环。无论如何任何帮助我如何能够实现这一点将不胜感激!

编辑**这是一个概念,所以你可以看到有时他们的钱箱将被检查与舒适性,有时它不会。 http://www.cancunelitetravel.com/ale/Capture.PNG

+0

它们必须插入mysql中的同一行。 – liveandream

回答

3

您对此的看法完全错误。如果您不确定可用的选项的数量,您应该这样写:

$cnt = 0; 
foeach ($_POST as $option => $value) { 
    if (preg_match("/(?:acharge|amenities)(\\d+)/", $option, $matches)) { 
     $cnt = max($cnt, intval($matches[1])); 
    } 
} 
for ($i = 0; $i < $cnt; $i ++) { 
    $amenity = $_POST['amenities' . $i]; 
    $value = "0"; 
    if (array_key_exists("acharge" . $i, $_POST)) { 
     $value = "1"; 
    } 
    mysql_query("INSERT INTO hotel_amenities (amenity_code, hotel_id, charge) VALUES ('$amenity','$hotel_id','$value')") or die(mysql_error()); 
} 

我认为这会为您做。假设您已经建立了连接并已考虑到$hotel_id的值。

+0

这是不完全正确的,$阿门是其他输入复选框,我需要得到。他们是两个。一个是酒店设施,另一个是旁边的复选框,这意味着它是否会收取额外费用。 – liveandream

+0

我添加了一个图像,以更好的想法。非常感谢! – liveandream

+0

我试过这个,并得到一个错误:警告:preg_match()[function.preg-match]:分隔符不能是C:\ wamp \ www \ olympus-backend \ inc \ add-hotel.php上的字母数字或反斜杠79行 – liveandream

相关问题