This is a tricky question to ask. A friend of mine seeks help, and I am not really into the project so it is difficult to describe the problem.
He has a shopping cart written in PHP, and in that shopping cart he wants all the product prices to be counted into a total price.
The problem is, all the prices are in a MySQL database. Displaying the prices (with decimals) is not a problem but, when these prices are counted and put in a variable, the decimals are not shown.
How can we solve this problem?
I will show you the code that he uses for displaying the prices in the shopping cart:
// Show cart
foreach($cart as $products) {
// Split
/*
$product[x] -->
x == 0 -> product id
x == 1 -> hoeveelheid
*/
$product = explode(",",$products);
// Get product info
$sql = "SELECT product_nummer, productnaam, verkoopprijs
FROM product
WHERE product_nummer = ".$product[0]; // Komt uit de sessie
$query = mysql_query($sql) or die (mysql_error()."<br>in file ".__FILE__." on line ".__LINE__);
$pro_cart = mysql_fetch_object($query);
$i++;
$price = $pro_cart->verkoopprijs; // variable price aanmaken zodat er opgeteld wordt
echo "<tr>\n";
echo " <td>"." • ".$pro_cart->productnaam."</td>\n"; // naam
echo " <td><input type=\"hidden\" name=\"productnummer_".$i."\" value=\"".$product[0]."\" />\n"; // wat onzichtbare vars voor het updaten
echo " <input type=\"text\" name=\"hoeveelheid_".$i."\" value=\"".$product[1]."\" size=\"2\" maxlength=\"2\" /></td>\n";
echo " <td class=\"rechtsuitlijnen\">"."€ ".$pro_cart->verkoopprijs."</td>"."\n";
$lineprice = $product[1] * $price; // regelprijs uitrekenen > hoeveelheid * prijs
echo " <td class=\"rechtsuitlijnen\">"."€ ".$lineprice."</td>\n";
echo " <td><a href=\"javascript:removeItem(".$i.")\">X</td>\n"; //Product verwijderen
echo "</tr>\n";
// Total
$total = $total + $lineprice; // Totaal updaten
}
?>
For displaying formatted numbers, you can use the PHP sprintf function ( http://php.net/manual/en/function.sprintf.php )
<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>
Use: bcadd()
echo bcadd(10.50, 12.75, 2);
returns 23.25
string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
Check out number_format documentation.
Related
I need to make this print a number with two decimal points, I believe I use this piece of code int $decimals = 0 but I don't know where I need to add it.
Here's the code I have:
<?php
$tempPrice = str_replace(',',"", $price); //gets rid of ","
$tempPrice = substr($tempPrice,2); //removes currency from the front
$tempPrice = floatval($tempPrice); //converts to double from string
if($tempPrice > 1000)
{
echo '£' . round(($tempPrice*0.038), 2) . ' per month';
}
else
{
echo 'Lease to buy price not available on this product';
}
?>
Thanks
You can use money_format() php function. http://php.net/money_format
for example in your case
<?php
$tempPrice = str_replace(',',"", $price); //gets rid of ","
$tempPrice = substr($tempPrice,2); //removes currency from the front
$tempPrice = floatval($tempPrice); //converts to double from string
// set international format for the en_GB locale
setlocale(LC_MONETARY, 'en_GB');
if($tempPrice > 1000)
{
echo money_format('%i', $tempPrice ) . " per month";// output->"GBP 1,234.56 per month"
}
else
{
echo 'Lease to buy price not available on this product';
}
?>
in addition you can just use php number_format() http://php.net/number_format on $tempPrice
echo "£ ". number_format($tempPrice ) . " per month";
by default number_format() english notation is used. You can set your own number of decimal points, decimal point setarator and thousands separator
echo "£ ". number_format($tempPrice, 2, ".", "," ) . " per month"; // for $tempPrice=1203.52 output will be "£ 1,203.56 per month"
how to set if price row is comming soon than show update soon
how to set if price row is comming soon than show update soon
mysql
<?
//connect to database
mysql_connect('localhost','phone','pasword');
mysql_select_db('phone');
//////Displaying Data/////////////
$id=$_GET['id']; // Collecting data from query string
if(!is_numeric($id)){ // Checking data it is a number or not
echo "Data Error";
exit;
}
$result = mysql_query("SET NAMES utf8"); //the main trick
$q=mysql_query("select * from price where id=$id AND TRIM(model) IS NOT NULL");
//Adds one to the counter
mysql_query("UPDATE price SET counter = counter + 1 where id=$id ");
//Retreives the current count
$count = mysql_fetch_row(mysql_query("SELECT counter FROM price"));
$row=mysql_fetch_object($q);
echo mysql_error();
echo "<table class='hovertable'><tr><td><img src='admin/media/$row->photo' ></td></tr>";
echo "</table>";
?>
example
my rows
2000
3000
comming soon
4900
and this code is showing like this
2000
2000
3000
Warning: number_format() expects parameter 1 to be double, string given in
4900
and i want like this
2000
2000
3000
update soon
4900
how to solve this problem please help me to solve this issue
<?php if($row->price):?><tr class=\"style1\"><td width='200'><b>Price US $:</b></td><td>Price in Dollar:
<?php
function currencyExchange($amount,$baseCurrency,$quoteCurrency) {
$open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$baseCurrency[0]$quoteCurrency[0]=X&f=sl1d1t1c1ohgv&e=.csv", "r");
$exchangeRate = fread($open, 2000);
fclose($open);
$exchangeRate = str_replace("\"", "", $exchangeRate);
$exchangeRate = explode(",", $exchangeRate);
$results = ($exchangeRate[1]*$amount);
$results = number_format ($results, 2);
$amount = number_format ($amount);
$timeStamp = strtotime($exchangeRate[2]);
$timeStamp = date('F d, Y', $timeStamp);
$timeStamp = "$timeStamp $exchangeRate[3]";
echo "$results\n";
}
// for additional currency ticker symbols visit: http://finance.yahoo.com/currency-converter
$usd = array('USD','US Dollars');
$INR = array('INR','Indian Rupees');
$usd = array('usd','US DOLLARS');
$b = str_replace( ',', '', $row->price );
if( is_numeric( $b ) ) {
$row->price = $b;
}
currencyExchange("$b",$INR,$usd);
?></td></tr><?php endif; ?>
Test if the amount is numeric before trying to use functions that only work for numbers.
Replace:
$results = ($exchangeRate[1]*$amount);
$results = number_format ($results, 2);
$amount = number_format ($amount);
with:
if (is_numeric($amount)) {
$results = ($exchangeRate[1]*$amount);
$results = number_format ($results, 2);
} else {
$results = 'update soon';
}
You don't need to call number_format() on $amount because you never print that value.
What about setting the column to something like 9999999999 ( which will get around numbers problem ) then testing the incoming for these numbers and if found then echo coming soon
I have tried for hours, and hope you can help me now :
I am trying to get values from a HTML form via $_POST into a table via PHP, and multiplying two numbers: ['amount'] * ['price'] = $totalprice
So far so good.
I get something that might look like this:
Description – Amount – Format – Price – Total ($totalprice)
Spoon – 3 – pieces – 4 – 12
Plate – 2 – pieces – 3 – 6
Glass – 6 – pieces – 3 – 18
Now how do I sum up all the “Total” ($totalprice)’s 12+6+18 so I get the result: 36 ?
The piece of code I’m struggling with:
foreach($_POST['description'] as $value)
{
echo "<tr><td>";
echo $i+1;
echo "</td>
<td>".$value."</td>
<td><center>".$_POST['amount'][$i]."</td>
<td><center>".$_POST['format'][$i]."</td>
<td><center>".$_POST['price'][$i]."</td>";
//Figures out the total price = amount * price
$x1 = $_POST['amount'] [$i];
$x2 = $_POST['price'] [$i];
echo "<td><center>";
$totalprice = $x1 * $x2;
echo $totalprice;
//Figures out the total price = amount * price
$i++;
}
You just need to sum all totals while iterating
$grand_total = 0;
foreach($_POST['description'] as $value)
{
echo "<tr><td>";
// code here...
$totalprice = $x1 * $x2;
echo $totalprice;
$grand_total = $grand_total + $totalprice;
$i++;
}
echo $grand_total;
use this code
$totalprice = 0;
foreach($_POST['description'] as $value)
{
echo "<tr><td>";
echo $i+1;
echo "</td>
<td>".$value."</td>
<td><center>".$_POST['amount'][$i]."</td>
<td><center>".$_POST['format'][$i]."</td>
<td><center>".$_POST['price'][$i]."</td>";
//Figures out the total price = amount * price
$x1 = $_POST['amount'] [$i];
$x2 = $_POST['price'] [$i];
echo "<td><center>";
$totalprice = $totalprice + ($x1 * $x2);
$i++;
}
echo $totalprice;
Hi Guys This is my newbie question...
I started learning php three days ago...
This is my problem...
for example
I have a quantity 50 when I subracted by 10 the value 50 became 40
and the notifier alert me that number is less than 50
but still subracted when I subract it again .....
Here is My codes
if(isset($_POST['submit'])){
$id = $_GET['id'];
$old = $_POST['quantity'];
$new = $_POST['quantity1'];
$total = $new - $old;
if($total < 50 ){
echo "<h1 style='color: red'><center>CRITICAL LEVEL</center></h1>";
echo "<script>window.open('inventory.php' , '_self');</script>";
}
else{
$uiqry = $mysqli->prepare("UPDATE table_inventory SET quantity = ? WHERE id = ?");
$uiqry->bind_param('ii', $total,$id);
$uiqry->execute();
$uiqry->close();
echo "<script>alert('Subracted');</script>";
echo "<script>window.open('inventory.php', '_self');</script>";
}
}
I want When I the value 50 and I subract it from 10 the value is now 40 and the alert notify me
and when i subract it again by 10 the value become 30 and the notify popup again
how to do this
thanks in advance..
Sorry for my tongue twister english.. :D
if(isset($_POST['submit'])){
$id = $_GET['id'];
$old = $_POST['quantity'];
$new = $_POST['quantity1'];
$total = $new - $old;
if($total < 50 ){
echo "<h1 style='color: red'><center>CRITICAL LEVEL</center></h1>";
echo "<script>window.open('inventory.php' , '_self');</script>";
}
$uiqry = $mysqli->prepare("UPDATE table_inventory SET quantity = ? WHERE id = ?");
$uiqry->bind_param('ii', $total,$id);
$uiqry->execute();
$uiqry->close();
echo "<script>alert('Subracted');</script>";
echo "<script>window.open('inventory.php', '_self');</script>";
}
'Ello
I'm trying to get the items from a client populated "order form" to ONLY list the items that the client has designated a quantity value of 1 or more to be sent as a Purchase Order receipt that is generated and sent via email once they hit Submit.
Here's what I have so far on that part:
$i = 1;
$imax = 4;
echo "Products<br />";
echo "-------------------------------------------------------------<br />";
while ($i <= $imax) {
$itemqty = ${'qty'.$i};
$itempn = ${'pn'.$i};
$itemdesc = ${'desc'.$i};
$itemprice = ${'value'.$i};
$itemtotalprice = ${'elinetotal'.$i};
if ($itemqty !== 0) {
echo $itemqty . " x " . $itemdesc . " (" . $itempn . ") # $" . $itemprice . " ea. = $" . $itemtotalprice . "<br />";
}
$i++;
}
It lists everything correctly, except it doesn't disregard the items with a value of 0. It'll list them like this:
Products
-------------------------------------------------------------
0 x Item #1 Description (HOSE-12) # $155.00 ea. = $0.00
5 x Item #2 Description (GAUGE-2) # $51.00 ea. = $255.00
0 x Item #3 Description (PTC) # $0.70 ea. = $0.00
10 x Item #4 Description (PT-234R) # $15.94 ea. = $159.40
It may be the easiest fix, but can anyone shed some light on this? I'd greatly appreciate it!
My initial guess is $itemqty is the string '0'. Try using the not equal operator, eg
if ($itemqty != 0)
instead of the not identical operator, ie !==
Otherwise, you could try casting the $itemqty assignment as an integer, eg
$itemqty = (int) ${'qty'.$i};