1
我有一個用逗號準備插入分隔成一個MySQL表的標籤名稱的字符串,例如:插入多條記錄
$tags = " 'pigs','dogs','cats' "
我有一個MySQL表稱爲標籤含有TAG_ID和tag_name。
我想插入每個標籤到表中。這是可能在一個INSERT查詢使用我有字符串,或者我將不得不運行一個循環與標籤名稱的數組?
我有一個用逗號準備插入分隔成一個MySQL表的標籤名稱的字符串,例如:插入多條記錄
$tags = " 'pigs','dogs','cats' "
我有一個MySQL表稱爲標籤含有TAG_ID和tag_name。
我想插入每個標籤到表中。這是可能在一個INSERT查詢使用我有字符串,或者我將不得不運行一個循環與標籤名稱的數組?
你可以這樣做:
$sql = "INSERT INTO `tags` (`tag_name`) VALUES(". implode('),(', explode(',', trim($tags))) . ")";
如果你是呼應了$sql
你應該得到:
INSERT INTO `tags` (`tag_name`) VALUES('pigs'),('dogs'),('cats')
它的代碼
<?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;
?>
看起來不錯,謝謝你。 – user1481563 2012-07-11 01:35:26
祝你好運,歡呼! – 2012-07-11 01:36:12