将逗号分隔的字符串插入多个列

时间:2017-01-09 17:09:21

标签: php

我正在寻找一个解决方案,我可以插入逗号分隔的字符串,但将它们拆分并插入到同一个表的不同列中。

我理解这可以实现,因为我已经浏览了整个网络,并且看到其他人可能成功地做到了这一点。

我有一个简单的<textarea name="stenData" placeholder="Paste Sten Data..."></textarea>

将要插入的数据始终与从另一个来源复制的数据相同,并且始终保持相同的格式。像这样:

RP1 = 8,RP2 = 3,RP3 = 1等等......

这将插入到包含samn列的成员表中,因此rp1rp2

目前我只是插入数据,但据我所知,你可以在发布的数据周围包含一个explode()函数?我正在寻找一些建议,而不是任何事情......

更新

我正在通过以下方式爆发POST输入:

$stenData = explode(',',  $_POST['stenData']);

这给了我(作为一个例子):

array(2) { [0]=> string(5) "RP1=8" [1]=> string(5) "RP2=7" }

但我不确定如何将其插入多列

**更新2 **

我正在尝试将数据插入到我的表中,因此我将从表单中发布数据,如下所示:

// Dashboard Name
$dashboardName = $_POST['dashboardName'];

// Member Details
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$score_1 = $_POST['score_1'];
$score_2 = $_POST['score_2'];
$score_3 = $_POST['score_3'];
$score_4 = $_POST['score_4'];
$score_5 = $_POST['score_5'];
$score_6 = $_POST['score_6'];
$score_7 = $_POST['score_7'];
$score_8 = $_POST['score_8'];
$stenData = explode('=',  $_POST['stenData']); // this is the problem line

// Team name
$teamName = $_POST['teamName'];

然后我尝试插入,除了stenData之外所有这些都没问题:

$sql2 = "INSERT INTO members (firstName, lastName, score_1, score_2, score_3, score_4, score_5, score_6, score_7, score_8, dashboard_id, rp_1) 
         VALUES ('$firstName', '$lastName', '$score_1', '$score_2', '$score_3', '$score_4', '$score_5', '$score_6', '$score_7', '$score_8', '$dashboard_id', '$stenData')"; 

错误消息为:Notice: Array to string conversion,它只是输入“&#39; array&#39;进入列行单元格。

1 个答案:

答案 0 :(得分:1)

$_POST['stenData'] = "RP1=8,RP2=3,RP3=1";
preg_match_all("|RP([0-9]+)=([0-9]+)|", $_POST['stenData'], $matches);
$tmpArr = array();
foreach($matches[1] as $key => $value)
{
    $tmpArr['RP'.$value] = $matches[2][$key];
}

结果:

array (size=3)
  'RP1' => string '8' (length=1)
  'RP2' => string '3' (length=1)
  'RP3' => string '1' (length=1)