Paul Ruocco Paul Ruocco - 1 month ago 5
PHP Question

How can I add a row within each step of a PHP prepared statement?

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?

Answer

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.

Comments