user1481563
user1481563

Reputation: 125

Inserting multiple records

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

Answers (2)

TaeL
TaeL

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

Marcus Recck
Marcus Recck

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

Related Questions