2016-12-06 41 views
-1

我有以下的複選框(從形式摘錄):插入多選框MySQL的PHP​​:只需要添加一個條目

<input type="checkbox" name="Cat_Ref_Array[]" value="2" /> 
<label for="Cat_Ref_Array[]">Category 2</label> 

<input type="checkbox" name="Cat_Ref_Array[]" value="3" /> 
<label for="Cat_Ref_Array[]">Category 3</label> 

<input type="checkbox" name="Cat_Ref_Array[]" value="5" /> 
<label for="Cat_Ref_Array[]">Category 5</label> 

<input type="checkbox" name="Cat_Ref_Array[]" value="7" /> 
<label for="Cat_Ref_Array[]">Category 7</label> 

<input type="checkbox" name="Cat_Ref_Array[]" value="13" /> 
<label for="Cat_Ref_Array[]">Category 13</label> 

而下面的PHP將其插入到表:

<?php 

$chkbox = $_POST['Cat_Ref_Array']; 
$i = 0; 

while ($i < sizeof($chkbox)) { 
    $insertSQL = sprintf(
     "INSERT INTO table (Data, `Call`, Cat_Ref) VALUES (%s, %s, %s)", 
     GetSQLValueString($_POST['Data'], "text"), 
     GetSQLValueString($_POST['Call'], "text"), 
     GetSQLValueString($chkbox[$i], "int") 
    ); 
    $result = mysql_query($insertSQL, $site) or die(mysql_error()); 
    $i++; 
} 

但是每次只插入一條記錄,不管勾選了多少個複選框?

怎麼回事?

+0

***請[停止使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。* ** [這些擴展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中刪除。瞭解[prepared](http://en.wikipedia。 org/wiki/Prepared_statement)語句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli .quickstart.prepared-statements.php)並考慮使用PDO,[這真的很簡單](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

你可以在$ chkbox中顯示數組嗎?我認爲你沒有得到你期望的。 –

回答

0

爲什麼不爲每一個簡單?

$chkbox = $_POST['Cat_Ref_Array']; 

foreach($chkbox as $value){ 
.... 
} 
+0

謝謝+蒂姆。最初,我只是不想重複「插入...」功能,但這只是工作! – user1259798

相關問題