简体   繁体   中英

PHP + MySQL: How to select values from a checkbox

The HTML:

<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>

The 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));
    ...
 }

The problem:

This let me do the query only when I select one checkbox, if I select 2 or more, it just takes the last selected value.

What am I missing there?

Thanks in advance.

This ought to work: using implode() to build the array into a string.

$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));

If your inputs are not numerals:

$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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM