如果用户不在特定表中,我会尝试将每个用户名插入 MySQL 数据库。否则,如果用户已经存在,则只需更新特定值(计数器增加 +1)。
我的问题是,它只插入一个用户,如果该用户在那里,则仅将值(+1)增加到该用户(最后插入的用户),而不会插入或更新到其他用户。
session :
$userName = $_SESSION['name'];
查询显示好友:
$query = "SELECT * FROM
users u
JOIN connections con on u.userName = con.Friend
WHERE u.userName = '$userName'
AND con.connectionStatus = '1'
UNION
SELECT * FROM
users u
JOIN connections con on u.userName = con.FriendReferee
WHERE u.userName = '$userName'
AND con.connectionStatus = '1'";
从连接表中获取好友:
$result = $conn->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$friends = $row["Friend"];
$friendRef = $row["FriendReferee"];
if ($userName == $friends) {
$userName = $friendRef;
} elseif ($userName == $friendRef) {
$userName = $friends;
}
}
}
将具有值的用户插入或更新到不同的表:
$result = $conn->query("SELECT id, userTo, counter FROM notbell WHERE userTo = '$userName'");
if($result->num_rows == 0 ) {
$sql2 = "INSERT INTO notbell (id, userTo, counter)
VALUES ('', '$userName', '1')";
} else {
mysqli_query($conn, "UPDATE notbell
SET counter = counter + 1
WHERE userTo = '$userName'");
}
执行查询:
if ( $conn->query($sql2) === TRUE) {
$prevUrl = $_SERVER['HTTP_REFERER'];
header('Location: '.$prevUrl);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
我认为我必须使用foreach
,但不知道该怎么做。
最佳答案
您可以使列名称userTo
在数据库中唯一,然后使用mysqli
的onDuplicate
函数
INSERT INTO notbell (id, userTo, counter) VALUES (', '$userName', '1')
ON DUPLICATE KEY UPDATE counter=counter+1;
关于php - 更新或插入mysql中每个用户的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491839/