0

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.

6
  • You must change the name attibute to something else so you can access them independently such as name="fooThis" and name="fooThat" etc... Commented May 2, 2013 at 2:07
  • 1
    @CorvinMcpherson - That's not correct; in HTML, IDs must be unique, but names do not need to be. Commented May 2, 2013 at 2:09
  • sir you might want to visit this stackoverflow.com/questions/16293024/… Commented May 2, 2013 at 2:15
  • @ChrisForrence Names dont have to be unique, but they can be, so you can easily extract them in php/asp/etc responses. Sorry, for the misleading "You must". Commented May 2, 2013 at 2:15
  • @CorvinMcpherson - I mean, sure, names can be unique. And in a small case such as this, it may be handy. But when it gets to many checkboxes, it can get out of hand readability-wise ;) Commented May 2, 2013 at 2:19

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

4 Comments

And how will you guard against SQL injection? ;)
OP's already using prepare(), assuming that class provides it. Chris does raise a good point though, make sure you are using prepared statements or otherwise escaping your inputs as you query the database.
PDO's prepare does guard against SQL injection...if you're using parameter markers (:boundvars or question marks). However, since the user input is both unescaped and unbound to the query, this particular query is unsafe.
@ChrisForrence Yeah. FIND_IN_SET() in this case is definately better. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.