doushishi2415 2018-08-21 17:43 采纳率: 0%
浏览 42
已采纳

来自PHP,SQL查询的好奇结果

I'm working on an experiment that works with database and I got this odd result.

System goes like this: I have a button that adds 1 to the counter every time you click it. Once it reach certain number, it will calculate score deduction and update the score

PHP:

$counter = $_POST['counter'];
$user = $_POST['user'];

$sql = "SELECT score FROM board WHERE player = '$user'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

if($counter == 1)
  $divisor = 0;
else if($counter == 5)
  $divisor = 0.1;
else if($counter == 20)
  $divisor = 0.3;
else if($counter == 50)
  $divisor = 1;}

$deduction = $row['score'] * $divisor;

$sql = "UPDATE board SET score = score - ".$deduction." WHERE player = '$user'";

I started with score = 10 and these are the results

Score: 10
Counter: 1

Divisor = 0; Deduction = 10 * 0;
UPDATE ... score = score - Deduction (0)
New score = 10
-------------------------------------

Score: 10
Counter: 5

Divisor = 0.1; Deduction = 10 * 0.1;
UPDATE ... score = score - Deduction (1)
New score = 9
-------------------------------------

Score: 9
Counter: 20

Divisor = 0.3; Deduction = 9 * 0.3;
UPDATE ... score = score - Deduction (2.7)
New score = 6.3
-------------------------------------

## Here is the curious part

Score: 6.3
Counter: 50

Divisor = 1; Deduction = 6.3 * 1;
UPDATE ... score = score - Deduction (6.3)
New score = 0.000000190735

Any idea as to why I'm getting the 0.000000190735? I'm kinda really confused right now.

B'rgrds,

  • 写回答

1条回答 默认 最新

  • dongzhe3171 2018-08-21 17:47
    关注

    This is a bit long for a comment.

    This is, no doubt, caused by different representations for score and $divisor or by the conversion of $divisor to a string for the query. It is hard to specify exactly where the problem is, because there are several different places.

    If you really need to handle this, do the calculations in the database:

    UPDATE board
        SET score = score * (1 - ?)
        WHERE player = ?;
    

    Pass the placeholders in as parameters -- rather than munging the query string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建