Paul Ruocco Paul Ruocco - 1 year ago 63
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:


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 Source

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->bind_result($value, $quantity);
    while($select -> fetch()){
        $subtotal = $value * $quantity;
        $total += $subtotal;
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download