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


insert multiple values in one column with 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…对于所有4个plot_id, booked_by_agent,id,totalamount是相同的。我想要这样

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

你更可能想要插入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字符串通常不是一个好主意,但如果不了解更多关于您的系统和您的需求是什么,很难说。

你可以像这样通过insert插入多行:

$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部分。

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

首先将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)
");

首先将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)");

else 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)");

首先需要为plot_id列分配varchar类型。然后你可以这样做。

假设plot 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)
");

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与相同的user id是否已经存在于数据库中,而不仅仅是添加相同的新id。