2016-09-28 5 views
1

У меня есть некоторые проблемы с моей корзиной покупок, она не суммирует все предметы, когда я их добавляю, а значение достигает около 1000/1400, сумма ошибочна, и она просто перестает суммировать предметы. Проверьте это изображение: http://prntscr.com/cn6uvgСумма PHP неверна, когда она достигает 1000

Там вы можете увидеть 2 пунктов со значением 1000, и он должен дать 2000, но вместо этого он дает 1001, и это происходит только тогда, когда сумма больше, чем около 1000.

<?php 
ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 
session_start(); 
include("admin/php/connect_to_mysql.php"); 
include("admin/php/myFunctions.php"); 
if(!empty($_GET['prodid'])){ 
    $pid = $_GET['prodid']; 
    $wasFound = false; 
    $i = 0; 
    if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){ 
     $_SESSION["cart_array"]=array(0=>array("productID"=>$pid,"quantity"=>1)); 
    }else{ 
     foreach($_SESSION["cart_array"] as $each_product){ 
      $i++; 
      while(list($key,$value)=each($each_product)){ 
       if($key=="productID" && $value==$pid){ 
        array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$pid,"quantity"=>$each_product ['quantity']+1))); 
        $wasFound=true; 
       } 
      }  
     } 
     if($wasFound==false){ 
      array_push($_SESSION["cart_array"],array("productID"=>$pid,"quantity"=>1)); 
     } 
    } 
    header("location:shoppingcart.php"); 
    exit(); 
} 
//------------------------------------------------------------------------------------------------- 
$submit = $_POST['btnUpdate']; 
if($submit == "Update"){ 
    $x = 0; 
    $i = 0; 
    //echo $_POST['txtQuan2']; 
    //echo $_POST['txtHoldProdId0']; 
    foreach($_SESSION["cart_array"] as $each_product){ 
     $i++; 
     $quantity = $_POST['txtQuan'.$x]; 
     $prodStock = $_POST['txtHoldQuan'.$x]; 
     $prodAdjustId = $_POST['txtHoldProdId'.$x++]; 
     if($quantity<1){ $quantity = 1; } 
     if($quantity>$prodStock){ $quantity = $prodStock; } 
     while(list($key,$value)=each($each_product)){ 
      array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$prodAdjustId,"quantity"=>$quantity))); 
     }  
    } 

} 
//------------------------------------------------------------------------------------------------- 
if(!empty($_GET['cid']) || isset($_GET['cid'])){ 
    $removeKey = $_GET['cid']; 
    if(count($_SESSION["cart_array"])<=1){ 
     unset($_SESSION["cart_array"]); 
    }else{ 
     unset($_SESSION["cart_array"]["$removeKey"]); 
     sort($_SESSION["cart_array"]); 
    } 
} 
//------------------------------------------------------------------------------------------------- 
$cartTitle = ""; 
$cartOutput = ""; 
$cartTotal = ""; 
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){ 
    $cartOutput="<h2 align='center'> Your shopping cart is empty </h2>"; 
}else{ 
    $x = 0; 
    $cartTitle .= '<form name="shoppingcart_form" action="shoppingcart.php" method="post" /><table width="700px" cellspacing="0" cellpadding="5"> 
      <tr bgcolor="#CCCCCC"> 
         <th width="220" align="left">Image </th> 
         <th width="140" align="left">Name </th> 
         <th width="100" align="center">Quantity </th> 
         <th width="60" align="center">Stock </th> 
         <th width="60" align="right">Price </th> 
         <th width="60" align="right">Total </th> 
         <th width="90"> </th></tr>'; 
    $i = 0; 
    foreach($_SESSION["cart_array"] as $each_product){ 
     $product_id = $each_product['productID']; 
     $sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1"); 
     while($row=mysql_fetch_array($sql)){ 
      $prodNo = $row["prod_no"]; 
      $prodID = $row["prod_id"]; 
      $prodName = $row["prod_name"]; 
      $prodPrice = $row["prod_price"]; 
      $prodQuan = $row["prod_quan"]; 
     } 
     $pricetotal=$prodPrice*$each_product['quantity']; 
     $cartTotal= number_format($pricetotal+$cartTotal,2); 
     $cartOutput .= '<tr><td><img style="border: 2px solid;" src="images/product/'.$prodNo.'.jpg" width="150" height="120" /></td> 
      <td>'.$prodName.'</td> 
      <td align="center"><input type="hidden" name="txtHoldProdId'.$i.'" value="'.$prodID.'" /><input name="txtQuan'.$i.'" type="text" value="'.$each_product['quantity'].'" style="width: 40px; text-align: center" /> </td> 
      <td align="center"><input type="hidden" name="txtHoldQuan'.$i.'" value="'.$prodQuan.'" /> <span style="color:#FF0000;">*Note</span></td> 
      <td align="right">$'.$prodPrice.'</td> 
      <td align="right">$'.$pricetotal.'</td> 
      <td align="center"> <a href="shoppingcart.php?cid='.$i++.'"><img src="images/remove_x.gif" alt="remove" /><br />Remove</a> </td></tr>'; 
    } 
    $_SESSION['checkoutCartTotal'] = $cartTotal; 
    $cartOutput .= '<tr> 
         <td colspan="3" align="right" height="40px">Have you modified your basket? Please click here to <input class="btn_upd" type="submit" name="btnUpdate" value="Update" />&nbsp;&nbsp;</td> 
         <td align="right" style="background:#ccc; font-weight:bold"> Total: </td> 
         <td colspan="2" align="left" style="background:#ccc; font-weight:bold;">$'.$cartTotal.' </td> 
         <td style="background:#ccc; font-weight:bold"> </td> 
        </tr> 
       </table> 

      <span style="color:#FF0000;"><p> *Note: If the item is not in stock, you should give us 12h to 24h to get it for you.</p></span> 
       <div style="float:right; width: 215px; margin-top: 20px;"> 

        <div class="checkout"><a href="checkout.php" class="more">Proceed to Checkout</a></div> 

       </div></form>'; 
} 

?> 

Код, указанный выше, является кодом моей корзины, в котором должно быть указано количество предметов. Посмотрите на этот экран: http://prntscr.com/cn6vlx

Это один является правильным, но если сумма достигает 1000 он перестанет работать:

http://prntscr.com/cn6vxe

И после достижения около 1000: http://prntscr.com/cn6wdg

+0

Напишите вот так: $ cartTotal + = $ pricetotal; и выполнить $ cartTotal за пределами цикла и проверить – premi

+0

Попробуйте изменить и сообщите нам об этом: '$ cartTotal = 0; // initialize $ pricetotal =! empty ($ pricetotal)? $ pricetotal: 0; $ cartTotal = $ pricetotal + $ cartTotal; $ cartTotal = number_format ($ cartTotal, 2); ' –

ответ

3

По умолчанию number_format($pricetotal+$cartTotal,2) не только обрезает два десятичных знака, , но и добавит разделитель тысяч.

Так 999 + 1 не даст «1000,0», а «1,000.0», который затем провалить сумму (так как это строка, а не «numbery» значение. Если оно рассматривается как число, это будет считаться 1, так же как 123 274 будет рассмотрено 123). Таким образом, у вас есть 1000 + 1000 на самом деле «1000,00» + 1000 и рассматривается как 1 + 1000; следовательно, 1001 вместо ожидаемого 2000.

TL; DR использовать только number_format в конце сценария. Если вам нужно округление, используйте round(), а не number_format. В худшем случае поддерживайте два разных значения: valueAsNumber (float) и valueAsString (строка, отформатированная). Затем вам придется синхронизировать их.

0

Нашли проблему я просто удалил «number_format», и теперь он работает, не уверен, почему, но он работает.

Смежные вопросы