gpt4 book ai didi

php - 如何使用 PDO 在一个数据库行程中插入多条记录?

转载 作者:行者123 更新时间:2023-11-29 17:30:45 25 4
gpt4 key购买 nike

我有一个名为 propAmenities 的表,其中包含两列 amenity_idproperty_id 基本上该表包含外键。

现在我必须使用以下语句的命名占位符生成 PDO 查询。

INSERT INTO propAmenities (amenity_id, property_id) VALUES (1, 1), (2, 1), (3, 1)

我尝试使用以下语法,但我不确定这是否有效。

$sth->$this->dbh->prepare('INSERT INTO 
propAmenities
(amenity_id, property_id)
VALUES
(:amenity_id, :property_id),
(:amenity_id, :property_id),
(:amenity_id, :property_id)');

对于上面的查询,我不确定如何使用 PDO 的 bindParam() ?我该如何使用 PDO 处理这种情况?我是否使用了错误的 PDO 占位符?

最佳答案

您可以为占位符指定任何您想要的名称,因此您的 SQL 如下所示:

INSERT INTO propAmenities 
(amenity_id, property_id)
VALUES
(:amenity_id1, :property_id1),
(:amenity_id2, :property_id2),
(:amenity_id3, :property_id3)

然后:

$stmt->bindParam(':amenity_id1',  1);
$stmt->bindParam(':property_id1', 1);
$stmt->bindParam(':amenity_id2', 2);
$stmt->bindParam(':property_id2', 1);
$stmt->bindParam(':amenity_id3', 3);
$stmt->bindParam(':property_id3', 1);

或者,当然,为执行构建适当的数组。在这种情况下,非命名占位符可能更容易使用:

INSERT INTO propAmenities 
(amenity_id, property_id)
VALUES
(?, ?),
(?, ?),
(?, ?)

然后您可以循环遍历您的值并使用适当的数组调用execute:

$stmt->execute(array(1, 1, 2, 1, 3, 1));

关于php - 如何使用 PDO 在一个数据库行程中插入多条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50683163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com