将相应的逗号分隔值插入其各自的数据库字段

时间:2018-02-09 21:46:00

标签: php mysql

我在输入字段文本框中有两个以逗号分隔的值,answersqid作为输入名称。

answers = abc,def,ghi
qid = 1,2,3

我想如何插入:

qid|answer
--------------
  1|abc
  2|def
  3|ghi

但根据代码,它同样为所有3个qids插入abc 对于所有3个qids,defghi,这样我得到9个元组而不是3个。

代码:

 $answers=$this->input->post("answers");
 $question=$this->input->post("qid");

$ans = explode(',',$answers); 
$qid = explode(',',$question); 

foreach($qid as $qids){
    foreach($ans as $anss){
    $data = array(
                'qid' => $qids,
                'user_answer'=>$anss,
            );
        $result = $this->db->insert("user_answer",$data);

    }

}

1 个答案:

答案 0 :(得分:0)

您只需要一个 foreach循环

注意:仅当 $ ans $ qid 记录匹配时才有效(两个数组中的记录数相同),否则可能行为不端!

$answers=$this->input->post("answers");
$question=$this->input->post("qid");

$ans = explode(',',$answers); 
$qid = explode(',',$question); 

foreach($qid as $k => $qids){
    $data = array(
                'qid' => $qids,
                'user_answer'=>$ans[$k],
            );
        $result = $this->db->insert("user_answer",$data);

}