如何使用PDO在一个数据库之旅中插入多个记录?

Ibr*_*mar 6 php mysql pdo

我有一个表propAmenities,其中包含两列amenity_id,property_id基本上该表包含外键.

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

INSERT INTO propAmenities (amenity_id, property_id) VALUES (1, 1), (2, 1), (3, 1)
Run Code Online (Sandbox Code Playgroud)

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

$sth->$this->dbh->prepare('INSERT INTO 
                           propAmenities 
                           (amenity_id, property_id) 
                           VALUES 
                           (:amenity_id, :property_id), 
                           (:amenity_id, :property_id), 
                           (:amenity_id, :property_id)');
Run Code Online (Sandbox Code Playgroud)

对于上述查询我不知道如何使用PDO的bindParam()?我如何处理这种情况使用PDO?我使用错误的PDO占位符吗?

mu *_*ort 5

您可以为占位符提供您想要的任何名称,以便为您的SQL提供以下内容:

INSERT INTO propAmenities 
(amenity_id, property_id) 
VALUES 
(:amenity_id1, :property_id1), 
(:amenity_id2, :property_id2), 
(:amenity_id3, :property_id3)
Run Code Online (Sandbox Code Playgroud)

然后:

$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);
Run Code Online (Sandbox Code Playgroud)

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

INSERT INTO propAmenities 
(amenity_id, property_id) 
VALUES 
(?, ?),
(?, ?),
(?, ?)
Run Code Online (Sandbox Code Playgroud)

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

$stmt->execute(array(1, 1, 2, 1, 3, 1));
Run Code Online (Sandbox Code Playgroud)