dplsnw7329 2014-09-28 04:37
浏览 53
已采纳

PDO for循环问题

I have a function that should calculate prices based on quantity.
The function should loop through every order and calculate every product price based on quantity, then should return order total price.
What i'm doing wrong?

public function getSumaComanda($cos) {
    $suma = $this->_db->query(sprintf("SELECT (@pretredus:=`pretredus`) AS `pretredus`,(CASE @pretredus WHEN 0 THEN `prettotal` ELSE `pretredus` END) AS `prettotal` , cantitate  FROM comenzi WHERE cos = '%d'", $cos));
    $suma->execute();
    $data_array = $suma->fetchAll(PDO::FETCH_ASSOC);

    $count = $this->_db->query(sprintf("SELECT COUNT(*) FROM cosuri WHERE id='%d'", $cos));
    $num = $count->fetchColumn();


    for ($x = 0; $x < $num; $x++) {
        $price = $data_array['cantitate'][$x] * $data_array['prettotal'][$x];
        $pret = $pret + $price;
        $pret = number_format($pret, 2, ".", "");

    }

    $rez = $pret;
    return $rez . ' Lei';
}
  • 写回答

1条回答 默认 最新

  • douwei7976 2014-09-28 07:39
    关注

    You should learn how to basically debug your variables. With using var_dump($data_array); you can see, what's in there.

    You have to use the numerical index first:

    $price = $data_array[$x]['cantitate'] * $data_array[$x]['prettotal'];
    

    Nevertheless, your second query is useless. You don't have to count the results and can use instead a while-loop:

    public function getSumaComanda($cos) {
        $suma = $this->_db->query(sprintf("SELECT (@pretredus:=`pretredus`) AS `pretredus`,(CASE @pretredus WHEN 0 THEN `prettotal` ELSE `pretredus` END) AS `prettotal` , cantitate  FROM comenzi WHERE cos = '%d'", $cos));
        $suma->execute();
    
        while ($data_array = $suma->fetch(PDO::FETCH_ASSOC)) {
            $pret += $data_array['cantitate'] * $data_array['prettotal'];
        }
    
        return number_format($pret, 2, ".", "") . ' Lei';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行