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

时间:2019-02-16 21:00:21

标签: php mysql insert updates

您好,感谢您抽出宝贵时间阅读这篇文章

我有一个客户数据库,一直在尝试添加一个忠诚度积分系统,以便订单总数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 = $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);

1 个答案:

答案 0 :(得分:0)

我想我会做一个选择来检查给定用户名是否已经有记录。如果存在,获取其分数,然后执行更新,将其他分数添加到其检索的总数中。如果没有记录,请插入。我很想写PHP和查询,但我只是在手机的atm上。希望这对以后有所帮助

(UPDATE)嗨,除了您可能希望将它们保留在单独的行中,因为可能会取消订单或发生其他事情(根据系统的“大”大小,这可能是有效的点),请分开。检查如何才能获得要求的功能。

请注意,自PHP 5.3起不推荐使用mysql_db_query,并且已从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);
}

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