douyingzhan5905 2017-02-13 05:43
浏览 27
已采纳

MySQL到PHP整数数学

I have a MySQL table with an integer column in it called count which I'm trying to do some basic math on and then update the value. Here is an example of one such task I'm trying to do.

$sql = 'SELECT count FROM triggers WHERE id = ?';
$params = array($id);
$result = sqlsrv_query($connection, $sql, $params);

$row = sqlsrv_fetch_array($result);

$count = intval($row[0]);
if ($count = 0)
   return -1;
$newCount = $count - 1;

$sql = 'UPDATE triggers SET count = ? WHERE id = ?';
$params = array($newCount, $id);
$result = sqlsrv_query($connection, $sql, $params);

The problem I'm having is that $newCount always equals -1, so the database value of count is updated to -1. In one particular example run, $count was equal to 84, so it passed the if statement. But then instead of $newCount being set to 83, it gets set to -1.

I have a feeling this has something to do with the MySQL value being treated as a string instead of an integer, but I thought intval() would solve that. I also tried using (int) instead, but no difference.

  • 写回答

3条回答 默认 最新

  • douan3019 2017-02-13 05:53
    关注

    Your problem is if ($count = 0). In PHP, = is the assignment operator and == is the equality comparison operator.

    tl;dr: You meant if ($count == 0).

    (Or if $count === 0. Although since $count is guaranteed to be an integer here, it won't really matter in this case. Using ===, and only explicitly using == where you intend to invoke type fiddling may also be a good habit to get into.)

    Explanation: Let's step through your code. What's happening here is:

    1. $count = intval($row[0]); sets $count to whatever value from the database.
    2. if ($count = 0) assigns the value of 0 to $count, regardless of anything else. It then tests this value of 0 which is falsey, causing the if statement block to be skipped and return -1 is never executed. This is the same as would happen if you directly wrote if (0).
    3. $newCount is assigned a value of $count - 1, or -1 in all cases since $count will always be 0.
    4. The query is then executed, UPDATEing the row with, none other than our friend -1.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应