php - 在循环中为每个用户存储值(value)

标签 php mysql arrays loops

在应用程序中,我有一个选择用户并选择类(class) ID。我想要做的是对于每个选择的用户,我想在数据库(MySQL)中创建新记录 已选择类(class) ID。为了更好地解释它应该是这样的:

数据库:

在此场景中,已选择 2 个用户和 2 个类(class),因此已创建 4 条记录:

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;
}

是因为我有一行$stmt->bind_param("ss", attendees[$i], Lesson_iDs[$i]);

如何更改此代码以执行我要求它执行的操作?我对 php 的经验很少,所以这就是为什么我问这样一个糟糕的问题

最佳答案

如果我理解您想要正确执行的操作,则问题不在于您的查询,而在于循环。如果您想要 user_id x Lesson_id 的笛卡尔积,则需要在循环中另一个循环。例如:

foreach ($users as $user_id)
{
    foreach ($lessons as $lesson_id)
    {
        $stmt->bind_param("ss", $user_id, $lesson_id);
        $stmt->execute();
    }
}

关于php - 在循环中为每个用户存储值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48784241/

相关文章:

c - 从 C 中的函数返回一个数组

PHP MySQL 事务捕获错误

php - 我可以在 PHP 中混合使用 MySQL API 吗?

php - 如何创建一个 laravel 哈希密码

python - 使用 Python Flask 向现有用户注册时 Web 应用程序显示数据库错误

MySQL InnoDB : Differences between WAL, 双写缓冲区、日志缓冲区、重做日志

javascript - 如何将 php 文件转换为 codeigniter

php - 如何从 php 创建新的 MySQL 数据库用户

java - 将字符串数组转换为 Map

java - 将有符号字节数组转换为 Int 数组