Laravel 5:从mysql db中的表单插入(嵌套)数组数据(从mysqli转换语法)

时间:2016-01-08 15:01:38

标签: php arrays laravel nested

我在将现有的mysqli语法转换为适合Laraval的格式时遇到问题。只要它有效,我很乐意使用原始查询。

我有这种mysqli语法(有效 - 但显然不是在Laravel中):

$outID = array_map($mysqli_escape, $_POST['outcomeid']);
$chID = array_map($mysqli_escape, $_POST['ChallengeRandom']);
$pts = array_map($mysqli_escape, $_POST['PropOutcomePts']);
$userID = array_map($mysqli_escape, $_POST['username']);
$timestamp = array_map($mysqli_escape, $_POST['ctime']);
$prID = array_map($mysqli_escape, $_POST['PropId']);
$crID = array_map($mysqli_escape, $_POST['CrushId']);

for($i=0;$i<count($outID);$i++) { 
$ins1 = 'INSERT INTO challenge_input (PropOutcomeId, ChallengeId, ChallengeUserId, InputTime, PropOutcomePts, PropId, CrushId) VALUES (\''.$outID[$i].'\', \''.$chID[$i].'\', \''.$userID[$i].'\', \''.$timestamp[$i].'\', \''.$pts[$i].'\', \''.$prID[$i].'\', \''.$crID[$i].'\')';
$query = mysqli_query($con,$ins1) or die(mysqli_error($con));
} 

上一页的表单输出如下所示(上下文:表单包含五个问题,每个问题都有四个答案选项(具有结果和结果)。只有在检查结果项时 - 即,选择的答案用户 - 是表单中传递的结果。):

Crushtime[]:2016-01-28 16:00:00
PropId[]:35
CrushId[]:13
username[]:16
ctime[]:2016-01-08 15:55:28
ChallengeRandom[]:db167049-b617-11e5-a
outcomeid[]:45
PropOutcomePts[]:200
PropOutcomePts[]:100
PropOutcomePts[]:100
PropOutcomePts[]:200
PropId[]:36
CrushId[]:13
username[]:16
ctime[]:2016-01-08 15:55:28
ChallengeRandom[]:db167049-b617-11e5-a
PropOutcomePts[]:100
PropOutcomePts[]:100
PropOutcomePts[]:50
outcomeid[]:52
PropOutcomePts[]:200
PropId[]:38
CrushId[]:13
username[]:16
ctime[]:2016-01-08 15:55:28
ChallengeRandom[]:db167049-b617-11e5-a
PropOutcomePts[]:100
outcomeid[]:54
PropOutcomePts[]:50
PropOutcomePts[]:100
PropOutcomePts[]:150
PropId[]:39
CrushId[]:13
username[]:16
ctime[]:2016-01-08 15:55:28
ChallengeRandom[]:db167049-b617-11e5-a
PropOutcomePts[]:100
PropOutcomePts[]:50
outcomeid[]:59
PropOutcomePts[]:100
PropOutcomePts[]:150
PropId[]:40
CrushId[]:13
username[]:16
ctime[]:2016-01-08 15:55:28
ChallengeRandom[]:db167049-b617-11e5-a
PropOutcomePts[]:200
PropOutcomePts[]:100
PropOutcomePts[]:50
outcomeid[]:64
PropOutcomePts[]:100

评论代码

foreach ($outID as $key => $n) {
    DB::insert('INSERT INTO challenge_input (PropOutcomeId, ChallengeId, ChallengeUserId, InputTime, PropOutcomePts, PropId, CrushId) VALUES (?,?,?,?,?,?,?)',
        array('outID' => $outID[$key], 'chID' => $chID[$key], 'userID' => $userID[$key], 'timestamp' => $timestamp[$key], 'pts' => $pts[$key], 'prID' => $prID[$key], 'crID' => $crID[$key]));
}

1 个答案:

答案 0 :(得分:0)

数组的键必须与列名匹配:

foreach ($outID as $key => $n) {
    DB::table('challenge_input')->insert(array('PropOutcomeId' => $outID[$key], 'ChallengeId' => $chID[$key], 'ChallengeUserId' => $userID[$key], 'InputTime' => $timestamp[$key], 'PropOutcomePts' => $pts[$key], 'PropId' => $prID[$key], 'CrushId' => $crID[$key]));
}