-1

Interesting issue here...don't know where the problem is because I am using the code from another site that I have. The first site works perfectly and no problems...but when I converted it over to my new site, the total price amount won't calculate properly.

QUESTION: Am I missing something when I switched over my code? If I put the code below into the while loop it works ok with only ONE item, but not multiple and it doesn't look right if I change the location to this.

<div class="column text-lg">Subtotal: <span class="text-medium">$<?php echo $totalamount; ?></span></div>

Here is some images and the code that I have:

enter image description here

enter image description here

OLD WORKING CODE:

<?php
if ( ! isset($totalamount)) {
$totalamount=0;
}
$totalquantity=0;
if (!session_id()) {
session_start();
}
include ('core/connectdb.php');
$sessid = session_id();
$query = "SELECT * FROM cart WHERE cart_sess = '$sessid'";
$results = mysqli_query($connect, $query) or die (mysql_query());
if(mysqli_num_rows($results)==0)
{
echo '<div id="content" class="float_r"><div align="center"><h3>Your cart is empty.</h3> You can find our items on our <a href="products.php">product page</a>.</div></div><div class="cleaner"></div>';
}
else
{
?>
<div id="content" class="float_r">
<div align="center"><h1>Shopping Cart</h1></div>
<table border="1" align="center" cellpadding="5">
<tr><td> Item Code</td><td>Quantity</td><td>Item Name</td><td>Price</
td><td>Total Price</td>
<?php
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
extract($row);
echo "<tr><td>";
echo $cart_itemcode;
echo "</td>";
echo "<td><form method=\"POST\" action=\"cart.php?action=change&icode=
$cart_itemcode\"><input type=\"text\" name=\"modified_quantity\" size=\"2\"
value=\"$cart_quantity\">";
echo "</td><td>";
echo $cart_item_name;
echo "</td><td>";
echo '$' . $cart_price . '';
echo "</td><td>";
$totalquantity = $totalquantity + $cart_quantity;
$totalprice = number_format($cart_price * $cart_quantity, 2);
$totalamount=$totalamount + ($cart_price * $cart_quantity);
echo '$' . $totalprice . '';
echo "</td><td>";
echo "<input type=\"submit\" name=\"Submit\" value=\"Change quantity\">
</form></td>";
echo "<td>";
echo "<form method=\"POST\" action=\"cart.php?action=delete&icode=$cart_itemcode\">";
echo "<input type=\"submit\" name=\"Submit\" value=\"Delete Item\"></form>
</td></tr>";
}
echo "<tr><td >Total</td><td>$totalquantity</td><td></td><td></td><td>";
$totalamount = number_format($totalamount, 2);
echo '$' . $totalamount . '';
echo "</td></tr>";
echo "</table><br>";
echo "<div style=\"width:400px; margin:auto;\">You currently have " .
$totalquantity . " product(s) selected in your cart</div> ";
?>
<table border="0" style="margin:auto;">
<tr>
<td><button style="font-family:verdana; font-size:150%;" onclick="goBack()">Go Back</button></td>
<td style="padding: 10px;">
<form method="POST" action="cart.php?action=empty">
<input type="submit" name="Submit" value="Empty Cart"
style="font-family:verdana; font-size:150%;" >
</form>
</td><td>
<?php include('cart_upload.php'); ?>
</td></tr></table>
</div>
<div class="cleaner"></div>
<?php
}
?>

NEW NON-WORKING CODE:

<?php
if ( ! isset($totalamount)) {
$totalamount=0;
}
$totalquantity=0;
if (!session_id()) {
session_start();
}
include ('core/connectdb.php');
$sessid = session_id();
$query = "SELECT * FROM cart WHERE cart_sess = '$sessid'";
$results = mysqli_query($connect, $query) or die (mysql_query());
if(mysqli_num_rows($results)==0)
{
echo '<div"><div align="center"><h3>Your cart is empty.</h3> You can find our items on our <a href="products.php">product page</a>.</div></div>';
}
else
{
?>
    <!-- Page Title-->
      <div class="page-title">
        <div class="container">
          <div class="column">
            <h1>Cart</h1>
          </div>
          <div class="column">
            <ul class="breadcrumbs">
              <li><a href="index.php">Home</a>
              </li>
              <li class="separator">&nbsp;</li>
              <li>Cart</li>
            </ul>
          </div>
        </div>
      </div>
      <!-- Page Content-->
      <div class="container padding-bottom-3x mb-1">
        <!-- Shopping Cart-->
        <div class="table-responsive shopping-cart">
          <table class="table">
            <thead>
              <tr>
                <th>Product Name</th>
                <th class="text-center">Quantity</th>
                <th class="text-center">Subtotal</th>
                <th class="text-center"><a class="btn btn-sm btn-outline-danger" href="#">Clear Cart</a></th>
              </tr>
            </thead>
            <tdbody>
            <?php
            while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
            extract($row);
            $cart_price = number_format($cart_price);
              echo '<tr>';
                echo '<td>';
                  echo '<div class="product-item"><a class="product-thumb" href="shop-single.php?item=' . $cart_itemcode . ' "><img src="' . $cart_imagename . '" alt="' . $cart_item_name . '"></a>';
                    echo '<div class="product-info">';
                      echo '<h4 class="product-title"><a href="shop-single.php?item=' . $cart_itemcode . ' ">' . $cart_item_name . '</a></h4>';
                    echo '</div>';
                  echo '</div>';
                echo '</td>';
                echo '<td class="text-center">';
                  echo '<div class="count-input">';
                  echo '$' . $cart_price . ' Each';
                      echo "<form method=\"POST\" action=\"cart.php?action=change&icode=
                            $cart_itemcode\"><input type=\"text\" name=\"modified_quantity\" size=\"2\"
                            value=\"$cart_quantity\"><br\><input type=\"submit\" name=\"Submit\" value=\"Update\">
                            </form>";
                  echo '</div>';
                echo '</td>';
                $totalquantity = $totalquantity + $cart_quantity;
                $totalprice = number_format($cart_price * $cart_quantity);
                $totalamount= number_format($totalamount + ($cart_price * $cart_quantity));
                echo '<td class="text-center text-lg text-medium">$' . $totalprice . '</td>';
                echo '<td class="text-center"><a class="remove-from-cart" href="cart.php?action=delete&icode=' . $cart_itemcode . '" data-toggle="tooltip" title="Remove item"><i class="icon-cross"></i></a></td>';
              echo '</tr>';
            }
}
?>
</tbody>
</table>
</div>
<div class="shopping-cart-footer">
<div class="column text-lg">Subtotal: <span class="text-medium">$<?php echo $totalamount; ?></span></div>
</div>
<div class="shopping-cart-footer">
<div class="column"><a class="btn btn-outline-secondary" onclick="goBack()"><i class="icon-arrow-left"></i>&nbsp;Back to Shopping</a></div>
<div class="column"><a class="btn btn-primary" href="#" data-toast data-toast-type="success" data-toast-position="topRight" data-toast-icon="icon-circle-check" data-toast-title="Your cart" data-toast-message="is updated successfully!">Update Cart</a><a class="btn btn-success" href="checkout-address.php">Checkout</a></div>
</div>
</div>
Robert Ames
  • 51
  • 1
  • 8
  • Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…”)` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. `mysql_error` is the wrong function to use here. – tadman Sep 27 '17 at 01:22
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Sep 27 '17 at 01:22
  • A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. – tadman Sep 27 '17 at 01:22
  • 1
    This code is in really rough shape, it's a stew of HTML, CSS, SQL, and PHP. Why not use a proven platform like [Magento](https://magento.com) to build off of, or at the absolute least something like [Laravel](http://laravel.com)? – tadman Sep 27 '17 at 01:24
  • Thank you all very much for your information on this...I really appreciate it and will do my best to implement all that you have mentioned. I'm still fairly new to doing secure code and am working with snippets found online. (Yes I understand its not the safest thing to do.) no important USER information is ever used in a query and is only collected during signup. No card information, addresses, etc are ever used in the checkout system on my end, only through PayPal. The reason coding is so mixed up is due to the mixture of it being mine as well as others work. Cleanup will happen later. – Robert Ames Sep 27 '17 at 01:40
  • Aside from the messed up aesthetics and security of the code...I'm still needing to know why my total price isn't showing correctly :). – Robert Ames Sep 27 '17 at 01:41
  • You'd save yourself a ton of trouble, and us a lot of headaches while trying to read this, if you organized it better. For example, close your PHP tag `?>` to revert to `echo` by default mode, avoiding the need to stab in backslashes for every single double quote. – tadman Sep 27 '17 at 01:47
  • Ok, thank you all again, I will start cleaning up my code and see if I can't get things working. Sorry if I made things a hassle for you all... :( – Robert Ames Sep 27 '17 at 02:06

2 Answers2

1

It looks like you're adding together formatted numbers, which is bound to be trouble. Don't do that. Keep your values as raw as possible internally and only format then if and when you display them to the user:

$totalquantity = $totalquantity + $cart_quantity;
$totalprice = $cart_price * $cart_quantity;
$totalamount = $totalamount + ($cart_price * $cart_quantity);

echo '<td class="text-center text-lg text-medium">$' . number_format($totalprice) . '</td>';

Remember, messy code is where bugs hide. Keep things clean, as if you're working in a kitchen. Always, always keep things organized. If you're stuck on a chunk of code and aren't sure why it works, the first thing you should do is clean it up. Then keep cleaning. Sometimes in the process of re-organizing the mistake becomes obvious.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

So I found out the problem...at the top of my page I had this code:

if ( ! isset($totalamount)) {
  $totalamount=0;
}

APPARENTLY for some reason the code was considering it to have value of 2.

Once I added this down towards the bottom before my while loop:

$totalamount=0;

Like magic it works properly now even with formatted numbers. I wanted to keep the formatted numbers since I didn't want any cents in my prices, just whole dollar amounts.

Robert Ames
  • 51
  • 1
  • 8