开发者

Text in front of variables inside a foreach loop

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜