2014-12-13 65 views
-1

使用foreach添加複選框值。複選框名是相同.. enter image description here如何在foreach中插入多個值

我想這

<?php 
// checkbox name is check[] 
$check = $_POST['check']; 
foreach($check as $checks => $checked) 
{ 
$value = $checked; 
$sql = mysql_query("INSERT INTO `db` (`db_column`) VALUES ('".$value."')"); 
} 
?> 
+0

化妝複選框作爲陣列 2014-12-13 08:28:03

+0

,讓我錯誤..無效的論據等等等等等等 – 2014-12-13 08:29:04

+0

檢查它我現在提交 – 2014-12-13 08:39:40

回答

4
 <form name="form1" action="count.php" method="POST"> 
     <input type="checkbox" name="check[]" value="your value"> 
     <input type="checkbox" name="check[]" value="your value1"> 
     <input type="checkbox" name="check[]" value="your value2"> 
     <button type="submit" name="btn">Ok</button> 
     </form> 
     <?php 
     if(isset($_POST['btn'])){ 
      $check = $_POST['check']; 
      print_r($check);foreach($check as $checks => $checked){ 
       $value = $checked; 

      $sql = mysql_query("INSERT INTO `db` (`db_column`) VALUES ('".$value."')"); 
      } 
     } 
     ?> 
+0

哥們我想插入數據庫中我不想顯示在數組中,告訴我有可能我print_r不適合這種情況 – 2014-12-13 08:39:39

+0

請嘗試一下... – 2014-12-13 08:44:18

+0

這是輸出哥們INSERT INTO'db'( db_column')VALUES('你的值') INSERT INTO'db'('db_column')VALUES('your value1') – 2014-12-13 08:48:37

0

PHP支持多維請求參數。但是你需要改變表單結構。我給你一個簡單的例子:

<?php 
if(isset($_POST) && isset($_POST['example_checkbox'])) { 
    foreach($_POST['example_checkbox'] as $key => $value) { 
     echo "The balue of $key is $value<br />"; 
    } 
    exit; 
} 
?> 
<html> 
    <head> 
     <title>Example</title> 
    </head> 
    <body> 
     <form method="post"> 
      <input type="checkbox" name="example_checkbox[checkbox_1]" value="1" />1<br /> 
      <input type="checkbox" name="example_checkbox[checkbox_2]" value="2" />2<br /> 
      <input type="checkbox" name="example_checkbox[checkbox_3]" value="3" />3<br /> 
      <input type="checkbox" name="example_checkbox[checkbox_4]" value="4" />4<br /> 
      <input type="checkbox" name="example_checkbox[checkbox_5]" value="5" />5<br /> 
      <input type="checkbox" name="example_checkbox[checkbox_6]" value="6" />6<br /> 
      <input type="submit" /> 
     </form> 
    </body> 
</html> 
+0

我的網頁是不是靜態我不能做那checkbox_1,checkbox_2他們應該是相同的,因爲他們可以超過6或在你的代碼中小於6我只能從6中獲得值。在我的頁面中,我至少從30個複選框中動態獲取價值 – 2014-12-13 08:36:39

+0

即使將名稱更改爲'example_checkbox []',該示例也可以工作 - 它是同樣的,唯一的區別就是循環中的$ key變量是一個整數,而不是一個字符串。 – 2014-12-13 08:39:12

+0

讓我檢查建議 – 2014-12-13 08:40:51