dpp78272 2016-10-07 21:04
浏览 19
已采纳

如何在PHP预处理语句的每个步骤中添加一行?

I have a prepared statement that produces a list of prices. The prices are determined by the value of the item multiplied by the quantity.

if ($select = $db -> prepare("SELECT value, quantity FROM items"))
{
    $select -> execute();
    $select -> bind_result($value, $quantity);
    while ($select -> fetch())
    {
        $subtotal = $value * $quantity;
        echo $subtotal.'<br />';
    }
    $select -> close();
}

// I want to put the $total here.

This outputs a list of numbers:

100
50
200
1.50

I would like to somehow add up each $subtotal and put them into another variable "$total" outside of my prepared statement. Is this possible to do WITHOUT doing the math within the query?

  • 写回答

1条回答 默认 最新

  • douxian4376 2016-10-07 21:08
    关注

    Declare a variable $total = 0 outside of the prepared statement and use it in the while() loop to calculate total price value, like this:

    $total = 0;
    if ($select = $db -> prepare("SELECT value, quantity FROM items")){
        $select->execute();
        $select->bind_result($value, $quantity);
        while($select -> fetch()){
            $subtotal = $value * $quantity;
            $total += $subtotal;
        }
        $select->close();
    }
    echo $total;
    

    Sidenote: As @Fred-ii and @JuanTomas mentioned, since you're using prepared statement without any placeholders, you could change ->prepare() to simply ->query() while removing the ->execute() statement altogether, it'll make no difference to your code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败