如何在新行中的每个部分插入逗号分隔的字符串到MySQL表中?

时间:2013-01-28 02:00:27

标签: php mysql loops explode

  

可能重复:
  Add new row in MYSQL from Comma Separated text in textbox
  Insert comma separated records in table

$words = 'word1,word2,word3';

如何将这些数据导入以下结构:

MySQL表:

id    value
 1    word1
 2    word2
 3    word3

我在想什么:

$separated = explode(",",$words);
//do some kind of loop
INSERT INTO table (value) VALUES ('$something');

我想我在循环中吮吸:/

由于

2 个答案:

答案 0 :(得分:2)

$wordArray = explode(",", $words);

$stmt = "INSERT INTO table (column) VALUES ('" . implode("'), ('", $wordArray) . "')";

这将产生:

INSERT INTO table (column) VALUES ('word1'), ('word2'), ('word3')

答案 1 :(得分:0)

做一个简单的循环,如下:

foreach($separated as $seperate){
    $sql .= "INSERT INTO table (value) VALUES ('$seperate')";
}