为什么我的 php 中的变量将自身重置为零?
这是一个错字问题,我真的不想把我的代码留在这里。这不会给其他任何人带来好处。
这是我的代码,我希望变量 $x 本身加上 $points 的值。由于某种原因,这是我得到的输出:
TOTAL Before Add: 0
points: 8
TOTAL after add: 8
TOTAL Before Add: 0
points: 32
添加后的总计:32
我希望这使得 x:40(添加 8+32)。
为什么x每次都从0开始?
感谢帮助, 右
This was a typo question and I didn't really want to leave my code up here. It would not benefit anyone else.
This is my code and I want the variable $x to be itself plus the value of $points. For some reason, this is the output I get:
TOTAL Before Add: 0
points: 8
TOTAL after add: 8
TOTAL Before Add: 0
points: 32
TOTAL after add: 32
I want this to make x: 40 (adding 8+32).
Why is x starting over at 0 again every time?
Appreciate the help,
R
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在代码中,您混淆了
$row3
和$row4
,但我假设您在此处迭代一行。另外,您似乎在这里提出了一个高度抽象的版本。验证即使在简化之后该错误是否仍然出现,例如使用测试数据库。但假设情况并非如此,唯一的解释是:您多次执行整个代码片段。每次执行时,它只读取一行。 添加
在 while 之前
,您将看到两次运行。最后一点,您实际上应该只在 2010 年后的代码中使用 PDO。它独立于数据库,并且对事务和预准备语句具有出色的支持。
针对编辑:
首先,您的代码容易受到SQL注入< /b>.现在修复这个问题,例如使用 PDO 准备好的语句。
其次,你为什么要加入php代码?您应该使用多个 JOIN 计算数据库中所需的总和和所有数据。为此,您不需要超过一个(也许是两个)SQL 查询。
第三,问题是你没有添加到 $total:
由于
$Total
未定义,它的计算结果为0
,所以你同样可以写:当然,你想要:
但正如我上面提到的,在应用程序而不是数据库中执行琐碎的计算(例如求和)仍然是一种非常糟糕的编码风格。
In the code, you confuse
$row3
and$row4
, but I'll assume you're iterating over one row here. Also, you seem to present a heavily abstracted version here. Verify that the bug appears even after the simplification, for example with a test database. But assuming that's not the case, the only explanation is:You're executing the whole code snippet multiple times. Each time it is executed, it reads exactly one line. Add
before the while and you'll see two runs.
As a final note, you should really only use PDO in post-2010 code. It is database-independent and has excellent support for transactions and prepared statements.
In response to the edit:
First of all, your code is vulnerable to SQL injection. Fix that now, for example by using PDO prepared statements.
Secondly, why are you joining in php code? You should calculate the sums and all the data you need on the database, with multiple JOINs. You should not need more than one(maybe two) SQL query for that.
Thirdly, the problem is that you're not adding to $total:
Since
$Total
is undefined, it's evaluated as0
, so you could equally write:Of course, you wanted:
But as I mentioned above, it's still an extremely bad coding style to perform trivial calculations (such as summing up) in the application instead of the database.