2013-05-02 103 views
0

的HTML:PHP + MySQL的:如何從一個複選框中選擇值

<form method="post" action="form.php"> 
    <input type="checkbox" name="foo[]" value="1"/>This<br/> 
    <input type="checkbox" name="foo[]" value="3"/>That<br/> 
    <input type="checkbox" name="foo[]" value="4"/>Those<br/> 
    <input id="btnClick" type="submit" /> 
</form> 

的PHP:

foreach ($_POST['foo'] as $va) 
{ 
    $stmt1 = $conn->prepare("select sum(field) from table where field2 in ($va)"); 
    $stmt1->execute($data1); 

    $result1 = $stmt1->fetchAll(); 
    print_r(var_dump($va)); 
    ... 
} 

問題:

這讓我只能做查詢時我選擇一個複選框,如果我選擇2或更多,它只需要最後選擇的值。

我在那裏錯過了什麼?

在此先感謝。

+0

您必須更改名稱attibute別的東西,所以你可以訪問它們獨立,如姓名=「fooThis」和名稱=「fooThat」等。 .. – 2013-05-02 02:07:15

+1

@CorvinMcpherson - 這是不正確的;在HTML中,ID必須是唯一的,但名稱不需要。 – 2013-05-02 02:09:14

+0

先生你可能想訪問這個http://stackoverflow.com/questions/16293024/multiple-checkbox-not-checking-after-submitting/16293187#16293187 – 2013-05-02 02:15:25

回答

2

這應該工作:使用implode()將數組構建成字符串。

$queries = implode(',', $_POST['foo']); 

$stmt1 = $conn->prepare("select sum(field) from table where field2 in ($queries)"); 
$stmt1->execute($data1); 

$result1 = $stmt1->fetchAll(); 
print_r(var_dump($va)); 

如果你輸入的不是數字:

$queries = implode("','", $_POST['foo']); 

$stmt1 = $conn->prepare("select sum(field) from table where field2 in ('$queries')"); 
$stmt1->execute($data1); 

$result1 = $stmt1->fetchAll(); 
print_r(var_dump($va)); 
+0

你將如何防範SQL注入? ;) – 2013-05-02 02:09:55

+0

OP已經在使用prepare(),假設類提供它。克里斯確實提出了一個很好的觀點,確保你使用了準備好的語句,或者在查詢數據庫時轉義輸入。 – 2013-05-02 02:10:16

+0

謝謝Set Sail Media,它的工作原理! – ramonovski 2013-05-02 02:13:12

相關問題