drcb19700 2018-02-14 09:58
浏览 24
已采纳

将值存储到循环中的每个用户

In the app I have a select users and select lesson id. What I want to do is for each user selected I want to create new records in the DB (MySQL) with each lesson id selected. To better explain this is what it should look like:

DB:

In this scenario, 2 Users and 2 lessons have been selected so 4 records have been created:

Date | User_ID | Lesson_ID
-----|---------|-----------
NOW()|67A62    |12
-----|---------|-----------
NOW()|220A0    |12
-----|---------|-----------
NOW()|67A62    |8
-----|---------|-----------
NOW()|220A0    |8

My Code:

In my code it goes through the list side by side. So the first user_id in the list will be assigned the first lesson_id in the list. Instead of what I want which is assign all the users from the user_id list each item (lesson_id) in the lesson_id list

My current php code for storing values in the MySQL DB:

public function storeClass($attendees, $lesson_iDs) {
    $stmt = $this->conn->prepare("INSERT INTO watch (date, user_id, lesson_id) VALUES(NOW(), ?, ?)");

    $i = 0;

    foreach ($attendees as $index => $attendee) {

        $stmt->bind_param("ss", $attendees[$i], $lesson_iDs[$i]);
        $i++;
        $result = $stmt->execute();
        // var_dump($i);

        if(!$result){
            echo 'Error: ' .$stmt->error;
        }
    }

    $stmt->close();

    // result
    return $result;
}

Is it because I have the line $stmt->bind_param("ss", attendees[$i], lesson_iDs[$i]);

How can I change this code to do what I require it to do? I have very little experience in php so that is why I ask such a bad question

  • 写回答

1条回答 默认 最新

  • douju4278 2018-02-14 10:18
    关注

    If I understand what you are trying to do correctly, the problem is not your query, but the loop. If you want to have a Cartesian product of user_id x lesson_id, you need another loop in your loop. For example:

    foreach ($users as $user_id)
    {
        foreach ($lessons as $lesson_id)
        {
            $stmt->bind_param("ss", $user_id, $lesson_id);
            $stmt->execute();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器