drz73366 2014-04-04 00:51
浏览 20
已采纳

插入多行的明智方法?

I have the following database relationship:

|--------|             |-----------------|            |-------|
| Groups | ------- 1.* | GroupMembership | *.1------- | Users |
|--------|             |-----------------|            |-------|

I have group ids in Groups, user ids in Users and the both of the in group membership, thus making a relationship between groups and users.

One record in GroupMembership looks like:

GroupID | UserID | datetime

I have an array posting from a form that looks like this:

["members"]=> array(5) { 
                          [0]=> "175" 
                          [1]=> "113" 
                          [2]=> "122" 
                          [3]=> "80" 
                          [4]=> "161"
}

Each value (175, 113 etc..) is a user ID. I need to insert a new row into the GroupMembership table for every ID in that array. How does one achieve such a task without kicking the ass out of the database and the servers resources?

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • duanjupiao4730 2014-04-04 00:57
    关注

    Four INSERT statements is not going to kill your server. Here is something you can do:

    ["members"]=> array(5) { 
          [0]=> "175" 
          [1]=> "113" 
          [2]=> "122" 
          [3]=> "80" 
          [4]=> "161"
    }
    
    $db = new PDO('mysql:host=localhost;dbname=yourdbname', $user, $password);
    $statement = $db->prepare("
            INSERT INTO GroupMembership(GroupID, UserId) VALUES (
                :__group_id,
                :__user_id
            )
        ");
    
    $statement->bindParam(':__group_id', $DEFAULT_GROUP_ID, PDO::PARAM_INT);
    $statement->bindParam(':__user_id', $user_id, PDO::PARAM_INT);
    for($i = 0; $i < count($members); $i++) {
        $user_id = $members[$i];
        $DEFAULT_GROUP_ID = <your_group_id>
        $statement->execute();
    }
    

    mysqli version

    $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
    $stmt = $mysqli->prepare("
           INSERT INTO GroupMembership(GroupID, UserId) VALUES (
               ?,
               ?
           )
     ")
    for($i = 0; $i < count($members); $i++) {
        $user_id = $members[$i];
        $stmt->bind_param('ii', $DEFAULT_GROUP_ID, $user_id);
        $stmt->execute();
    }
    $stmt->close();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵