find the total values get in a variable in php
i am doing a shopping cart.i had a variable $total.when i add 1st product of price 200 i get $total=200 , when i add 2nd product of price 100 i get $total=200100 when i add 3rd product of price 400 i get $total=200100400 . i want to get $total=700. how to fix this problem?
session_start();
$ar20=Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'price WHERE id="'.$_SESSION['y'].'" AND prodid="'.$row['id_product'].'" ORDER BY size DESC');
for($i=0;$i < count($ar20);$i++)
{
$test=$test+$ar20[$i]['price'];
}
开发者_C百科 $row['price'] += $test ;
$row['total'] = $row['price'] * intval($row['quantity']);
if 3 products then echo the $row['total'] will get this 100200300
Use +
instead of .
operator
Just get the value of price each time and add it in previous on like wise, the below logic may help u
say $newprice
is a variable where u get the price..
$total = 0;
$total +=$newprice;
Are you doing this?
$total = '100';
$total += '300';
$total += '300';
echo $total;
PHP is forgiving to a point, especially to the JavaScript fans: It allows you to use the + operator as concatenation if the operands are both strings. Make sure that you don't surround them in quotes, single or double, like so:
$total = 100;
$total += 300;
$total += 300;
echo $total;
Your code isn't clear because it has no context, but this should work:
$test = (integer) $test;
for($i=0; $i < count($ar20); $i++)
{
$test = $test + (integer) $ar20[$i]['price'];
}
$row['price'] = (integer) $row['price'] + (integer) $test;
$row['total'] = $row['price'] * intval($row['quantity']);
session_start();
$records=Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'price WHERE id="'.$_SESSION['y'].'" AND prodid="'.$row['id_product'].'" ORDER BY size DESC');
$row = array();
$test = '0';
if (count($records) < 1) {
$row['price'] = '0';
$row['total'] = '0';
} else {
foreach($records as $record)
{
$test = bcadd($test, $record['price']);
}
$row['price'] = bcadd($row['price'], $test);
$row['total'] = bcmul($row['price'], $row['quantity']);
}
PHP: bcadd
精彩评论