如何在同一条 mysql 记录中插入和更新数字?

How can I insert and update a number within the same mysql record?

您好,感谢您花时间阅读本文post

我有一个客户数据库,并且一直在尝试添加一个忠诚度积分系统,以便总订单 x 价值 = 总忠诚度积分

我让它正常工作,因此当收到订单时,它会用积分更新 table_loyalty,并且工作正常

$points = $row["price"] * 1000;

$insert = mysql_db_query($db, "INSERT into table_loyalty (username, orderno, points) VALUES ('$username', '$this_orderno', '$points')", $connection);
check_mysql($insert); 

然而,我最希望能够做到但似乎无法让它发挥作用(尝试了几种不同的方法)是总计 运行,这样每个额外的订单都会增加提高 $points 而不是添加单独的记录

我不是程序员,我确信这是显而易见的,但我将不胜感激任何帮助。

我已经试过了,但没有成功:

$points = $row["points"];

$newpoints = $row["price"] * 1000;

$update = mysql_db_query($db, "update table_loyalty set points='$points'+'$newpoints' WHERE username='$username'", $connection);
check_mysql($update);

} else {

$insert = mysql_db_query($db, "INSERT into table_loyalty (username, orderno, points) VALUES ('$username', '$this_orderno', '$newpoints')", $connection);
check_mysql($insert);

我想我会做一个 select 来检查是否已经有给定用户名的记录。如果有,获取它的点数,然后执行更新,将额外的点数添加到它检索到的总数中。如果没有记录,则插入。我很想写 php 和查询,但我只是在我的 phone atm 上。希望这有助于稍后检查

(UPDATE) 嗨,马克,除了您可能希望将它们分开的行之外,因为订单可能会被取消或发生其他事情(这可能是有效的点,具体取决于 'big' 您的方式system 是。让我们检查一下如何让要求的功能正常工作。

请注意,mysql_db_query 自 PHP 5.3 以来已被弃用,并已从 PHP 7.0.0 中完全删除。因此,如果您希望能够在长 运行 上完成这项工作,我建议您使用 http://php.net/manual/en/book.mysqli.php

我的建议如下:

$selectQuery = "SELECT points FROM table_loyalty WHERE username=" . $username . ";"

$selectResult = mysql_db_query($db, $selectQuery, $connection);

// if no results could be found
if (mysql_num_rows($selectResult) == 0) {
  //Presuming this is the order price?
  $newpoints = $row["price"] * 1000;

  $insertQuery = "INSERT into table_loyalty (username, orderno, points) VALUES ('$username', '$this_orderno', '$newpoints')";
  $insertResult = mysql_db_query($db, $insertQuery, $connection);
  // I personally have no idea what the check_mysql() function does, I presume its a function of you own making? With that I'm making the assumption that it handles the result in some way? 
  check_mysql($insertResult);

//results have been found
} else {
  $existingPoints = 0;
  while ($row = mysql_fetch_assoc($result)) {
    //There is a catch here. If used in this way you need to make sure that every username only has 1 entry in the table_loyalty. So updating only 1 row per user also means you can ONLY have 1 record per user.
    $existingPoints = $row["points"];
  }

  $newPoints = $row["price"] * 1000;
  $totalPoints = $existingPoints + $newPoints;
  $updateQuery = "update table_loyalty set points='$totalPoints' WHERE username='$username'";

  $update = mysql_db_query($db,updateQuery , $connection);
  check_mysql($update);
}

这是你可以使用的东西吗?这不是最优雅的解决方案,但从根本上讲,这就是您可能想要的 :)。