dpdfh60088 2011-06-04 08:33
浏览 20
已采纳

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

i have a table called propAmenities which holds two column amenity_id and property_id basically the table holds the foreign keys.

now i have to generate a PDO query using named placeholder for the below statement.

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

i tried using the following syntax but i am not sure if this will work.

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

and for the above query i am not sure how do i use PDO's bindParam() ? how do i handle this situation Using PDO? am i using the wrong PDO's Placeholders?

  • 写回答

2条回答 默认 最新

  • dongyi4420 2011-06-04 08:42
    关注

    You can give the placeholders whatever names you want so something like this for your SQL:

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

    And then:

    $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);
    

    Or, of course, build the appropriate array for execute. In this case, non-named placeholders might be easier to work with though:

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

    And then you can loop through your values and call execute with the appropriate array:

    $stmt->execute(array(1, 1, 2, 1, 3, 1));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看