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

eyh26e7m  于 2023-03-07  发布在  Mysql
关注(0)|答案(6)|浏览(117)
    • 此问题在此处已有答案**:

Is storing a delimited list in a database column really that bad?(10个答案)
4小时前关门了。
这是我的疑问

$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
x6h2sr28

x6h2sr281#

您很可能希望插入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字符串通常不是一个好主意-但如果不了解您的系统和您的需求,这很难说。

llycmphe

llycmphe2#

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

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

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

fjnneemd3#

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

8yoxcaq74#

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

q8l4jmvw5#

第一件事是需要为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)
");
xtupzzrd

xtupzzrd6#

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:或者,您可以从数据库中检查具有相同user idagent id是否已存在于数据库中,而不是仅添加具有新ID的相同。

相关问题