tags:

views:

28

answers:

2

I have set up a small script to handle a page where I have three checkboxes.

The HTML for the checkboxes looks like this:

<input type="checkbox" value="Ex1" name="Check[]" />Ex1
<input type="checkbox" value="Ex2" name="Check[]" />Ex2
<input type="checkbox" value="Ex3" name="Check[]" />Ex3

And the PHP script for these:

if($_POST['Check'] == true){
foreach($_POST['Check'] as $value){
$check_msg .= "$value";
}
}

Now, what I want to do is insert "Ex1, Ex2" into my database, if the "Ex1" and "Ex2" checkboxes were checked. But the problem is, if I put ", " in front of "$value", it will insert ", Ex1, Ex2" to the database. But as I said, I want to insert it without the comma and space in the beginning... How could I do something like this? It doesn't matter if it's a foreach loop or another method, because I really don't know any other method to check which checkboxes were checked.

I have tried a few combinations but couldn't really get the results I wanted...

Thanks.

+4  A: 

You can do it without foreach with implode. If the checkbox wasn't checked, there will be no value for it in the $_POST['Check'] value anyway.

Example:

$csv = implode(', ', $_POST['Check']);

Make sure you sanitize the resulting string before inserting it to the database to prevent SQL Injection.

Gordon
Sorry, I'm really new to PHP scripting. Uhm, how do I 'sanitize' those?
Nisto
Lovely and simple - nice!
Dave Rix
@Nisto read the [Wikipedia article about SQL Injection](http://en.wikipedia.org/wiki/SQL_injection) first to get an idea what it is and then have a look around [SO for how to sanitize variables](http://stackoverflow.com/search?q=sanitize+values+php).
Gordon
Thanks, I'll look into it!
Nisto
A: 

I always do that type of action with the following code;

foreach ( $_POST['Check'] as $key => $value ) {
  $check_msg .= ", {$value}";
}

$check_msg = substr($check_msg,2);

The last line just removes the ", " from the string you are building. Simpler and easier [IMHO] than checking the existing value of $check_msg every time you want to add the next item to it.

Dave Rix
Forget my method! Gordon's is much cleaner :)
Dave Rix
@DaveRix it's fine, but you could just use `trim($check_msg, ', ')` instead of `substr`. On a another sidenote, if you are not using `$key` there is no need to include it and you do not need the `{}` around `$value` either.
Gordon
Thanks for all your help :)
Nisto