在创建MySQL查询以更新用户的多个选择或其他建议方面需要帮助
我有一个页面,用户可以选择3至6个兴趣点,通过点击动态生成的按钮。我已经能够成功地将所选兴趣插入到数据库中,但我正在尝试为用户可能希望更新其先前选择的场景做准备。对于如何编写SQL查询或如何让用户更新他们以前选择的兴趣,有什么建议吗?从“利息”表中查询利息,表中的列为:id - name - description - navigation - seo_name和所选兴趣将插入member_interests表,表中的列为:interest_id - member_id。我能够通过删除以前选择的兴趣并创建新的兴趣来解决它。但我觉得这条路不太好走。
public function getAll(): array
{
$sql = "SELECT id, name, description, navigation, seo_name
FROM interest;"; // SQL to get all interest
return $this->db->runSQL($sql)->fetchAll(); // Return all interest
}
public function create(int $interestId, int $memberId): bool
{
$sql = "INSERT INTO member_interests (interest_id, member_id)
VALUES (:interest_id, :member_id);"; // SQL
$params = array('interest_id' => $interestId, 'member_id' => $memberId);
$this->db->runSQL($sql, $params); // Run SQL
return true; // Return true
}
public function deleteByMember(int $memberId): void
{
$sql = "DELETE FROM member_interests WHERE member_id = :member_id";
$params = [
'member_id' => $memberId
];
$this->db->runSQL($sql, $params);
}
..{
$checkedCount = count($interestsChosen);
if ($checkedCount < 3 || $checkedCount > 6) {
$errors['message'] = 'Please select 3-6 interests.'; // If the number of selected interests is less than 3 or more than 6, set the error message to 'Please select 3-6 interests.'
} else {
// Check if the user has previously chosen interests
$previousInterests = $cms->getInterest()->getInterestName($cms->getSession()->id);
$previousInterestIds = array_column($previousInterests, 'interest_id');
if (count($previousInterestIds) > 6) {
$errors['message'] = 'You can only choose up to 6 interests.'; // Set error message if user has already chosen interests and the total exceeds 6
} else {
// Delete existing interests for the user
$cms->getInterest()->deleteByMember($cms->getSession()->id);
// Iterate over the chosen interests and create them
foreach ($interestsChosen as $interestId) {
$cms->getInterest()->create(intval($interestId), $cms->getSession()->id);
}
if ($previousInterestIds) {
// User had previously chosen interests, redirect to interests updated page
redirect('interest-updated/', ['success' => 'Interests updated!']);
} else {
// User didn't have previously chosen interests, redirect to the next step in the onboarding process
redirect('onboard-occupation/');
}
}
}
}
1条答案
按热度按时间bfrts1fy1#
我有一个类似的表,为了简化代码,我删除了所有当前用户值,并添加了所有新值。
关于这种方法的公平警告:
1.这不一定是最有效的方法,但它节省了您对现有值的阅读和比较,因此它将负担从代码推到数据库。如果您不经常更新这个列表,并且列表很小,就像您的场景所显示的那样,那么对性能的影响是最小的,并且减少的代码负担是值得的。
1.如果服务器停止或在删除和写入之间发生故障,则可能会丢失数据。在我的情况下,这种风险是可以接受的,在你的情况下似乎也是如此。
您可以通过在一个命令中执行所有插入操作来略微降低数据库影响。
SQL