4

I have a form on my website, that uses an array to submit checkbox data. I then try to manipulate that data with a foreach loop to add a ":" to each checkbox data, and then I want to make that into a single string I can insert into a database.

This is my HTML code:

while($row = $result->fetch_assoc())
{
echo '<tr><td><input type="checkbox" name="pluginlist[]" value="'.$row['plugin'].'" /></td><td> '.$row['plugin'].'</td></tr>';
}

$row['plugin'] is data from a different table in the database.

This is my PHP code that $_POST the data, and then runs the foreach loop:

if(!empty($_POST['pluginlist'])) {
        foreach($_POST['pluginlist'] as $plugins) {
            $plugins1 = $plugins.":";
            }
            echo $plugins1;
}

The echo $plugins1 only echos the last checkbox data with a ":" on the end.

How can I make it so I can insert all the checkbox data into a database at once?

1
  • should be $plugins1 .= $plugins . ':"; in other words, you are not appending the previous string - missing .= . note you could use implode without a loop: $plugins1=implode(':',$_POST['pluginslist']); Commented Mar 27, 2013 at 0:07

3 Answers 3

3

You can serialize the data, I find that much more convenient!

Or you can try

$plugins1 = implode(":" , $_POST['pluginlist']);
Sign up to request clarification or add additional context in comments.

Comments

3

Concatenate the values. Otherwise you're assigning a new value to $plugins1 at each iteration.

$plugins1 .= $plugins.':'; // Correct - note the extra dot before the equal sign

And not:

$plugins1 = $plugins.':'; // Incorrect - would "reset" the value each time

Alternatively, you can also use implode to concatenate all array values to a single string:

$plugins1 = implode(':', $_POST['pluginlist'])

Comments

1

Is this what you're trying to do? I might not have understood your problem. The dot before the equals will concat but you might just want to implode.

$plugins1 = '';
if(!empty($_POST['pluginlist'])) {
        foreach($_POST['pluginlist'] as $plugins) {
            $plugins1 .= $plugins.":";
            }
echo $plugins1;
echo "<br />or<br/ >";
$plugins2 = implode ($_POST['pluginlist'], ':');
echo $plugins2;

1 Comment

Heh, I forgot they changed the arguments on implode... It should be glue and then array, but fortunately the function fixes this up for you. I guess the answer is answered before I could finish typing.

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.