0

is it possible to implode a checkbox value into multiple values to insert into a database?

At current I have this:

$tags = implode(', ', $_POST['checkboxname']);

This gives me the value of "testtag1, testtag2"

How would I split this up so it would go into the database like:

Blog ID ¦ Tag
------------------
1       ¦ testtag1

1       ¦ testtag2

Not sure how to make the implode function seperate them as this:

$query2 = mysqli_query($myConnection, "INSERT INTO blogtags (blogid, tag) VALUES('$blogid','$tags')") or die (mysqli_error($myConnection));

just inserts the two values together in one row.

Any help would be great! Thanks

2
  • Why do you implode? Simply itterate through $_POST['checkboxname']and do an insert in each loop. Commented Apr 19, 2013 at 13:07
  • 2
    Firstly, you have a huge SQL injection hole. Secondly, think about the MySQL syntax for inserting multiple rows in a single query - that's what you would need your string to look like. Thirdly, and most importantly because it solves both of the above and more: You should prepare a statement to insert a single row and invoke it multiple times. This is exactly what prepared statements are designed for. Commented Apr 19, 2013 at 13:07

1 Answer 1

2

Try this example:

$tags = $_POST['checkboxname'] ; //Take the array of tags.
$id = 1 ;                        //Set needed id.

$values = array() ;

foreach($tags as $tag){
  $tag = $myConnection->real_escape_string($tag);
  $values[] = " ('{$id}', '{$tag}') " ;
}

$values = implode(" , ", $values) ;
$query = "INSERT INTO blogtags (blogid, tag) VALUES {$values} ; " ;
Sign up to request clarification or add additional context in comments.

3 Comments

Saving comma-separated values in a database is often a bad idea. A better option is to save a different record for each tag.
@Jocelyn If you run this code, you will see, that it makes different records for each tag.
Ah yes, you are right. I had seen implode and implied you were imploding the tags. Using multi-insert as you do is fine. I should have read the code more carefully.

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.