Reputation: 125
I have a string with tag names separated by comas ready for insertion into a MySQL table, for example:
$tags = " 'pigs','dogs','cats' "
I have a mySQL table called tags containing a tag_id and tag_name.
I want to insert each tag into the table. Is this possible in one INSERT query using the string I have, or will I have to run a loop with an array of the tag names?
Upvotes: 1
Views: 55
Reputation: 1066
it's code
<?php
$tags = " 'pigs','dogs','cats' ";
$ary_tags = explode(",", trim($tags));
$sql = "INSERT INTO `tags` (`tag_name`) VALUES";
foreach($ary_tags as $t) {
$sql .= "({$t}),";
}
$sql = rtrim($sql, ',');
$sql .= ';';
echo $sql;
?>
Upvotes: 0
Reputation: 5065
You could do:
$sql = "INSERT INTO `tags` (`tag_name`) VALUES(". implode('),(', explode(',', trim($tags))) . ")";
And if you were to echo out $sql
you should get:
INSERT INTO `tags` (`tag_name`) VALUES('pigs'),('dogs'),('cats')
Upvotes: 3