Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
Why do you implode? Simply itterate through $_POST['checkboxname']and do an insert in each loop. –  Patrik Mayer Apr 19 '13 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. –  DaveRandom Apr 19 '13 at 13:07

1 Answer 1

up vote 2 down vote accepted

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} ; " ;
share|improve this answer
    
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 Apr 19 '13 at 13:46
    
@Jocelyn If you run this code, you will see, that it makes different records for each tag. –  Jari Apr 19 '13 at 13:47
    
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. –  Jocelyn Apr 19 '13 at 13:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.