我目前正在尝试创建一个系统,该系统从表“ users”中随机选择一个用户,并将其附加到另一个表“ agreeuser”或“ disagreeuser”中,具体取决于该用户是否具有“ opinion”值“喜欢”或“不喜欢”。我这样做是通过使用$ row选择用户认为“喜欢”的整行,但似乎并没有将存储在“ $ row [用户名]”中的数据添加到“用户”列中'agreeuser'或'disagreeuser'表的
。我已经尝试过将'$ row ['username']值存储为变量,并在查询的值方面使用它,但是似乎没有用。我也尝试过合并INSERT和SELECT查询,但仍然没有效果。有人可以告诉我我在做什么错吗? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
我需要将“用户”中的用户名插入“ agreeuser”的“用户”列中。感谢您的任何帮助,如果我做的很愚蠢,我深表歉意:)
答案 0 :(得分:0)
为什么不使用SQL视图仅在“虚拟表”中查看所需的数据,而不是创建重复的数据?
Views是非常有用的功能。
例如,进行SELECT查询以查找所需的行:
SELECT * FROM users WHERE opinion = 'dislike'
如果此选择适合您,只需添加:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
对于同意的用户也要这样做:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
说实话,我不明白为什么您要随机选择并只逐一插入用户。
如果您只想获得一个随机用户,只需在创建上面提到的视图后运行此查询即可:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
祝你好运! :)