php - 更新或插入mysql中每个用户的信息

标签 php mysql foreach

如果用户不在特定表中,我会尝试将每个用户名插入 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在数据库中唯一,然后使用mysqlionDuplicate函数

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/

相关文章:

php - 未找到 Laravel Lumen Memcached

javascript - 出现错误时将输入字段更改为不同的颜色

Mysql查询以查找具有所有给定权限的用户

php - 如果 preg_match 不匹配模式,则取消设置数组?

javascript - 如何在 Node.Js 的 forEach 中使用 Select Query?

php - 为什么我的 MySQL 查询这么慢?

php - 将 MySQL 数据标记为 'read'

MySQL 选择每个 id 具有最新值的所有行

mysql - 如何将 yyyy/mm/dd 转换为 dd/mm/yyyy?

java - Java中的for-each表达式翻译成什么?