使用mysql在一列中插入多个值

时间:2014-05-29 06:16:57

标签: php mysql

这是我的查询

$this->db->query("insert into
    booking (plot_id,booked_by_agent,id,totalamount)
    values ($a,$agent_id,$userID,$totalamount)
");

我想在plot_id字段中插入4个plot_id'例如1,2,3,4 ...和booked_by_agent,id,totalamount对于所有4个plot_id都是相同的。我想要这样

plot_id   booked_by_agent   id      totalamount
1,2,3,4       23            12       100000

6 个答案:

答案 0 :(得分:0)

您可以通过插入插入多行,如下所示:

$this->db->query("insert into
    booking (plot_id,booked_by_agent,id,totalamount)
    values
        ('$a[0]','$agent_id',$userID,$totalamount),
        ('$a[1]','$agent_id',$userID,$totalamount),
        ('$a[2]','$agent_id',$userID,$totalamount),
        ('$a[3]','$agent_id',$userID,$totalamount)
");

您可以使用foreach循环生成VALUES部分。

请更改数组索引以匹配您的数组!

答案 1 :(得分:0)

你很可能想要插入4行,例如:

plot_id   booked_by_agent   id      totalamount
------------------------------------------------
    1        23             12       100000
    2        23             12       100000
    3        23             12       100000
    4        23             12       100000

您的查询将如下所示:

INSERT INTO booking (plot_id, booked_by_agent, id, totalamount) 
VALUES 
    (1, 23, 12, 100000), 
    (2, 23, 12, 100000),
    (3, 23, 12, 100000),
    (4, 23, 12, 100000);

否则,正如评论中所述,您需要将plot_id的数据类型更改为varchartext。虽然,存储id的字符串通常不是一个好主意 - 但是如果不了解更多关于你的系统以及你的需求,很难说。

答案 2 :(得分:0)

首先将plot_id列更改为varchartext数据类型,并将所有值添加到此类字符串中

$plotid = $plot_id1.",".$plot_id2.",".$plot_id3.",".$plot_id4;

现在插入此$plotid代替$a。 现在你的查询将是

$this->db->query("insert into
    booking (plot_id,booked_by_agent,id,totalamount)
    values ('$plotid','$agent_id',$userID,$totalamount)
");

答案 3 :(得分:0)

首先将您的plot_id字段数据类型更改为varchar 然后,如果您的plot_id字符串为102,请尝试

function stringToArray($s)
{
    $r = array();
    for($i=0; $i<strlen($s); $i++) 
         $r[$i] = $s[$i];
    return $r;
}
$a = "102";
$arr = stringToArray($a);
$a = implode(',', $arr);
$this->db->query("insert into booking (plot_id,booked_by_agent,id,totalamount) values ('$a','$agent_id',$userID,$totalamount)");

否则plot_id将逐一出现,然后尝试用逗号分隔: -

$a = $plot_id1.",".$plot_id2.",".$plot_id3.",".$plot_id4;
$this->db->query("insert into booking (plot_id,booked_by_agent,id,totalamount) values ('$a','$agent_id',$userID,$totalamount)");

答案 4 :(得分:0)

首先,您需要为plot_id列指定varchar类型。 然后你就可以做到这一点。

假设情节ID来自数组。

$a = array(1,2,3,4);
$a = implode(',',$a);
$this->db->query("insert into
     booking (plot_id,booked_by_agent,id,totalamount)
    values ('$a',$agent_id,$userID,$totalamount)
");

答案 5 :(得分:0)

1:你可以像这样使用while循环

$a = 1; while ($a<=4){ $this->db->query("insert into booking (plot_id,booked_by_agent,id,totalamount) values ($a,$agent_id,$userID,$totalamount) "); $a++; }

2:或者您可以从数据库中检查数据库中是否已存在具有相同agent id的{​​{1}},而不仅仅是添加相同的新ID。