在应用程序中,我有一个选择用户并选择类(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/