【问题标题】:How to insert comma separated string into MySQL table while each part in new row? [duplicate]如何在新行中的每个部分将逗号分隔的字符串插入 MySQL 表? [复制]
【发布时间】:2013-01-11 08:15:44
【问题描述】:

可能重复:
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');

我想我很讨厌循环:/

谢谢

【问题讨论】:

  • 如果你知道你需要一个循环,写一个看看会发生什么。如果它不起作用,请向我们展示您所拥有的,我们可以为您提供帮助。但是至少尝试一下
  • 做怪胎循环。如果你suck at loops在循环页面打开怪胎手册,阅读,使用它,你就会成为循环大师

标签: php mysql loops explode


【解决方案1】:
$wordArray = explode(",", $words);

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

这将产生:

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

【讨论】:

    【解决方案2】:

    做一个简单的循环,像这样:

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

    【讨论】:

    • 这是低效的;您应该在一份声明中发送它们。见this
    • 是的,很快就能搞定
    • 不要使用@ 来抑制错误。它使调试变得困难。
    • @JohnConde 不确定为什么要编辑帖子以添加 @。还添加了引号...
    • @njk 并不总是可以使用仅作为存根添加的单个语句
    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多