【问题标题】:wrong result when using assignment operators in codeigneter在 codeigniter 中使用赋值运算符时结果错误
【发布时间】:2015-03-01 04:36:39
【问题描述】:

从数据库mysql 计算总计结果时遇到问题。我使用codeigneternewbei

这是我的数据库:

selldate | sell
--------------
 9 2014  |  20
10 2014  |  25    
11 2014  |  15

$n2 = -1;

$selling = $this->db->query("select sell as Y , date_format((selldate),'%M %Y') as month  from selling where id='$id' and selldate between '$dt1' and '$dt2'");

foreach ($selling->result() as $row){
    $u = $n2++;
    $t = $u*2+1;
    $yt = $row->Y * $t;
    $t2 = $t*$t;
    $r = 0;
    $r += $yt;
    $w = 0;
    $w += $t2;
    ?>
    <tr>
    <td><?php echo $row->month;?></td>
    <td><?php echo $row->Y;?></td>
    <td><?php echo $t;?></td>
    <td><?php echo $yt;?></td>
    <td><?php echo $t2;?></td>
    </tr>
    <?php 

    }; ?>
    <tr>
    <td></td>
    <td>Grand Total</td>
    <td></td>
    <td><?php echo "Grand Total is $r";?></td>
    <td><?php echo "Grand Total is $w";?></td>
    </tr>
    </table>

问题出在$r += $yt;$w +=$t2;它计算表的总计。

当我使用$r=0;$w=0; 时,我得到了错误的总计结果,但是当我删除$r=0;$w=0; 时,只使用$r+=$yt 只有我得到true 总计结果,但是有错误提示

严重性:通知 消息:未定义变量:r

【问题讨论】:

  • $r=0;$w=0; 放在foreach 循环之外/之前。 IE。把它放在$n2 = -1;

标签: php mysql codeigniter operators variable-assignment


【解决方案1】:

就像 Sean 所说的,您必须将 $r=0 和 $w=0 放在 for 循环之外,并放在 $n2 = -1 旁边。

目前发生的情况是每次 for 循环迭代 $r 并且 $w 变为 0。因此你得到一个错误的答案。那就是问题所在。一旦你在外面声明 $r 和 $w 为 0 就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 2021-10-31
    • 2013-12-04
    • 2014-12-26
    • 1970-01-01
    • 2012-05-26
    • 2011-02-08
    • 2020-01-30
    相关资源
    最近更新 更多