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 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题