【问题标题】:PHP is concatenating instead of addingPHP是连接而不是添加
【发布时间】:2013-01-06 01:51:39
【问题描述】:

我遇到了这个问题,我的 PHP 代码是连接而不是添加

$offset=$_POST['offset']; //Get the offset
$searchLimit = 10;
$searchCount = count(sql) //For the purpose of this question, it returns the result count

现在我想计算分页的“来自”显示,所以我这样做了

$from = ($offset*$searchLimit)+1;

$offset == 0

我得到预期的结果是 1。但是当

$offset == 1

它给了我 101。基本上它将 10 和 1 连接起来给我 101。我尝试了以下方法

$from = (int)($offset*$searchLimit)+1
$from = ((int)($offset)*$searchLimit)+1
$from = (((int)($offset)*$searchLimit)+1)

我什至尝试过

$offset = (int)$_POST['offset'];

但是他们都给出了相同的结果。

【问题讨论】:

  • 你看过PHP的intval函数吗? php.net/manual/en/function.intval.php
  • 我有 .. 在写此评论之前实际上已经尝试过了 .. 所以这就是我尝试过的... $from = (intval($offset*$searchLimit)+1) 但这也无济于事 ..
  • 我会尝试$offset = intval($_POST['offset']);
  • $from = ($offset*$searchLimit)+1; '工作正常' 如果它返回0,如前所述? (0*10)+1 == 1 确定吗?
  • 对不起..这又是我问这个问题的错误..它返回 1,这是预期的结果..我会在问题中纠正同样的问题..我也会尝试把intval around $_POST['offset'] .. 我最初尝试过$offset = (int)$_POST['offset'] 但这并没有做任何不同的事情..

标签: php concatenation


【解决方案1】:

您在searchLimit 之前缺少$。结果,它被视为字符串。这会导致意外行为。

【讨论】:

  • sql 之前也可能缺少美元符号。如果您启用了 PHP 的 display_errors 设置并将 error_reporting 设置为包含 E_NOTICE,您很快就会发现这个问题。
  • 对不起 .. 缺少的 '$' 是一个错字.. 我的代码中确实有它.. sql 行只是一个伪行。它不是应用程序中的实际 LOC。它是返回搜索结果计数的行。
【解决方案2】:

您在 searchLimit 之前(可能在 sql 之前)错过了一个 $ 符号。 -_-

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多