Jump to content

ford not updating quantity


roldahayes

Recommended Posts

Hi,

 

I have this code that runs a simple shopping cart.

 

I'm having an issue where the basket quantities are only updating when there is 1 or 2 lines of products in there.

 

Any more than that and the line keep defaulting back to quantity 1

 

Is there anything obvious that I have got wrong here?

 

Thanks.

 

<?phpheader("Content-type: text/html; charset=utf-8");session_start(); include_once("head.php");include_once("usr_conn.php");if(!connectDB()) { echo "<p>Unable To Connect To Database</p>"; return; }     if (isset ($_GET['src']))   {     $_SESSION['returnTo'] = $_GET['src'];   } $urlref = $HTTP_REFERER; $prodID = htmlentities ($_GET['productID']); $delete = htmlentities ($_GET ['delete']); $quantity = htmlentities ($_GET['quantity']); $updateQuantity = htmlentities ($_GET['updateQuantity']); $update = htmlentities ($_GET ['update']); $currency = "£"; // maximum querys per user basket $MAXBASKETQUERY = 25; // start the html table?>  <?php// check if user has no cookie set if ($userID == "") { ?><div class="alert alert-danger">No Product Querys made yet </div>                 <?php return; } //if the updated quantity is 0 or blank remove item from basket if ($updateQuantity == '0'){ $delete = 'yes'; } if (($update == 'yes')&& ($updateQuantity == '')){ $delete = 'yes'; } // if delete parameter set to yes run the delete code if ($delete == 'yes') { // if prodID is set, delete that specific product from this userID's basket if ($prodID != "") { $sqlquery = "DELETE FROM basket WHERE userID = '" . $userID . "' AND  productID = '" . $prodID . "'"; $result = mysql_query($sqlquery); if ($result) { ?>                                      <div class="alert alert-danger">Item Deleted. Click <a href="update.php"><font color="#990000">Here</font></a> to refresh the basket </div><?php } else { ?>                 <div class="alert alert-danger">Unable To Delete <br />                       Item Click <a href="update.php">Here</a> to refresh                                              the basket</div>                 <?php }   mysql_close(); return; } } //update the shopping basket quantity if ($update == 'yes') { // if prodID is set, delete that specific product from this userID's basket if ($prodID != "") { $sqlquery = "UPDATE basket SET quantity = '" . $updateQuantity . "' WHERE productID = '" . $prodID . "'AND userID = '" . $userID . "'"; $result = mysql_query($sqlquery); if ($result) { ?>                 <div class="alert alert-danger">Your basket has been updated.</div>                 <?php } else { ?>                 <div class="alert alert-danger">Your basket has NOT been updated</div>                 <?php }   } } // find the number of rows in this userID's basket $sqlquery = "SELECT * FROM basket WHERE userID = '" . $userID . "'"; $result = mysql_query($sqlquery); if (!$result) { echo "<p><font class=error>Could not find any entrys for this Basket</small></p>"; mysql_close(); return; } else $rowCount = mysql_num_rows($result); // if prodID is set new product is passed in, add/update the userID's basket if ($prodID != "") { // find if the prodID already exists in this userID's basket $sqlquery = "SELECT * FROM basket WHERE userID = '" . $userID . "' AND productID = '" . $prodID . "'"; $result = mysql_query($sqlquery); $rowCount = mysql_num_rows($result); // if no matches  insert the product into the userID's basket if ($rowCount == 0) { // find number of items in basket $sqlquery = "SELECT * FROM basket WHERE userID = '" . $userID . "'"; $result = mysql_query($sqlquery); $rowCount = mysql_num_rows($result); // check if the maxquery's has been reached if ($rowCount > ($MAXBASKETQUERY - 1)) { echo ("<p><font class=error>Only $MAXBASKETQUERY overall orders are allowed, your product could not be added to basket</font></p>"); } else { $expiretime = time() + 7200; $sqlquery = "INSERT INTO basket" . $basketFields . "VALUES ('" . $prodID . "', '1', '" .$userID . "', '" . $expiretime . "')"; $result = mysql_query($sqlquery); if (!$result) echo "<font class=error><p>Could not add item to Basket</p></font>"; } } } // select the userID's basket query and the Product Reference relating to each of the basket's productID's $sqlquery = "SELECT products.Prod_REF, basket.productID, basket.quantity, products.Prod_Make, products.Prod_Model, products.Prod_Type, products.Car_Make, products.Car_Model, products.Price_ExVat, products.Post_ID, Product_Desc FROM basket INNER JOIN products ON basket.productID = products.Prod_ID WHERE ((basket.userID) = '" . $userID . "')"; $result = mysql_query($sqlquery); $rowCount = mysql_num_rows($result); // echo $sqlquery;  // *debug // assign the table headers //$dbFields = array( "Reference", "Product Query"); // check if no entries in basket if (!$result || (mysql_num_rows($result) == 0)){ ?>                 <div class="alert alert-danger">No Product Queries                                              In Basket.</div>                 <?php } else //*************display contents of basket////////////////////////////////////////////////////// { // echo each header from array //foreach ($dbFields as $headIndex) // echo an extra blank header for the delete item column // fetch each row as an associative array $counter = 1; $price = 0; //set default postage value outside loop$postagerate = 15.00; while ($row = mysql_fetch_assoc($result)){  //decide which postage value is the highest and use that to calculate overall price  //get the postage values for each product  $sqlpostquery = "SELECT * FROM postage WHERE Post_ID = '" . htmlspecialchars($row['Post_ID']) . "'";   //get the postage values from the database  $postresult = mysql_query($sqlpostquery);  $rowpost = mysql_fetch_assoc($postresult);   // check if postage value was available  if ($postresult || !(mysql_num_rows($postresult) == 0))    {    $rawpostage = htmlspecialchars($rowpost['Post_Cost']) ? htmlspecialchars($rowpost['Post_Cost']) : 0.00;     //get the lowest postage rate.    if ($postagerate > $rawpostage)      {        $postagerate = $rawpostage;    }  }  else  {    $postagerage = 0.00;  }   //round postage rate of 2 decimal places  $postagerate = $postagerate;   //release the postage resultset array   mysql_free_result($postresult);   echo "<form action=basket.php method=get name=form".$counter.">     <input name=update type=hidden value=yes>     <input name=productID type=hidden value=". $row['productID'] ."><tr class=stdtable>";          ?>  <form method="post" action="">                                                                                                                                  <table border="0" cellspacing="0" cellpadding="0" width="100%" class="responsive shop_table cart" data-responsive-mode="stack">    <thead>      <tr>        <th>Part No.</th>        <th >Description</th>        <th>QTY</th>        <th>ex vat</th>        <th>inc vat</th>        <th>Total Price</th>        <th>Remove</th>                              </tr>    </thead>    <tbody>      <tr>                                 <!-- This is the block that will echo the basket columns  -->         <td class= partno table-striped mb-none><?php echo("" . htmlspecialchars($row['Prod_REF']) . "");?></td>         <td class= descrip table-striped mb-none><?php echo("" . htmlspecialchars($row['Product_Desc']) . "");?></td>         <td class= table-striped mb-none><?php echo (" <input name=updateQuantity onchange=submit(); type=text size=2 value=". htmlspecialchars($row['quantity']));?> </td>         <td class= table-striped mb-none><?php echo ("". $currency . number_format(htmlspecialchars($row['Price_ExVat']), 2) ."");?></td>         <td class= table-striped mb-none><?php echo ("". $currency . number_format(calcVAT($row["Price_ExVat"]), 2) ."");?></td>         <td class= table-striped mb-none><?php echo ("". $currency . number_format(((calcVAT($row["Price_ExVat"]* $row['quantity']))), 2) ."");?></td>         <td class= table-striped mb-none><?php echo "   <a href=\"basket.php?delete=yes&productID=" . $row['productID'] . "\">  <i class=\"fa fa-times\">"; ?></td>      </tr>                                            </table>                                               <!-- End of this section  -->                                                                    <?php    $counter ++;   //get a cumulative value of the price as items are added to the basket and multiply by quantity as we go.   $price = $price + (calcVAT (htmlspecialchars($row['Price_ExVat']))) * htmlspecialchars($row['quantity']);  } //assign subtotal and round to 2 decimal places $subtotal = $price; $total = $subtotal + $postagerate; //pick overall postage type if ($postagerate == 5) $postage = 3; else if ($postagerate == 9) $postage = 2; else if ($postagerate == 10) $postage = 1; } //update shopper table with new/changed info $sqlshopper = "SELECT * FROM shopper WHERE User_ID = '" . $userID . "'"; //echo "query: " . $sqlshopper; $result = mysql_query($sqlshopper); $rowCount2 = mysql_num_rows($result); //add shopper if ($rowCount2 == 0) { $sqladd = "INSERT INTO shopper" . $shopperFields . "VALUES ('" . $userID . "', '" . $total . "', '" . $postage . "')"; //echo "noshopper: " . $sqladd; $shopadd = mysql_query($sqladd); if (!$shopadd) echo "<font class=error><p>Your basket has not been processed</p></font>"; } else { //update details $sqlupdate = "UPDATE shopper SET Basket_total = '" . $total . "', Postage = '" . $postage . "' WHERE user_ID = '" . $userID . "'"; //echo "shopper: " . $sqlupdate; $shopupdate = mysql_query($sqlupdate); if (!$shopupdate) echo "<font class=error><p>Your basket has not been updated</p></font>"; } // finish table ?>                                                                                                                                                                        <?php  echo $currency;  echo number_format($subtotal, 2);  ?></span></td></tr><tr class="shipping" style="font-size: 18px"><th>Delivery</th><td><span class="header"> <?php  echo $currency;  echo number_format($postagerate, 2);  ?></span></td></tr><tr class="total"><th><strong>Order Total</strong>(inc vat)</th><td><strong><span class="amount"><?php  echo $currency;  echo number_format($total, 2);  ?></span></strong>                                  </form><?php   mysql_free_result($result);   mysql_close(); ?>

Link to comment
Share on other sites

i'm surprised you are still trying to get this code to work. you could have completely rewritten it by now and gotten it to do what you want.

 

even ignoring that your programming editor is using line endings that are non-standard, resulting in the forum software adding over 600 blank lines that we have to wade through, this code is disorganized to the the point that i cannot even determine where to look to find what may be causing the symptom you are asking about and it's so disorganized that you cannot troubleshoot it or isolate just the relevant part to post for us to consider.

 

you need to organize and separate the different concerns in the code, this will make it easier to write, change, or debug. see the following post for a layout suggestion - http://forums.phpfreaks.com/topic/297824-database-issues-and-working/?do=findComment&comment=1519095

 

in addition to just the organization of the code, here are some specific things i see in the code that either won't work or are contrary to good programming -

 

1) you are using a get method form to alter data on the server. a post method form should be used (you even have two nested <form> tags, which are invalid and the inner one is using method='post', which has no effect, because the first <form tag with method='get' wins.)

 

2) htmlentities() is an output function, not an input function. using it on the input data isn't going to protect against sql injection. you need to properly escape/case input data or use prepared queries to protect against sql injection.

 

3) you have some variables - $HTTP_REFERER and $userID that unless you are using an old version of php, these don't exist, which may be the cause of the symptom you are asking about.

 

4) your database statements don't have any error checking logic and the msyql_ database statements are obsolete and will be removed from php fairly soon.

 

5) your queries for inserting/updating the rows in the basket should be replaced with a single INSERT ... ON DUPLICATE KEY UPDATE query. there's no need to first try to select a row, then either insert or update the row. just run a single INSERT ... ON DUPLICATE KEY UPDATE query. with the appropriate index set up, it will insert a row if it doesn't exist or update it if it does.

 

6) item #5 would also apply to your 'shopper' table, which i'm guessing is an order table? if the information in the 'shopper' table is just derived information, you shouldn't have the table at all.

Link to comment
Share on other sites

 

 

i'm surprised you are still trying to get this code to work. you could have completely rewritten it by now and gotten it to do what you want.

 

​Ha! Thats what I am finally getting round to doing! 

 

Please ignore the html and the way I have posted, I have just cleared out the code to post here.

 

I'll go through your post and see what I can do,

 

Many thanks for helping (again) :)

Link to comment
Share on other sites

rather than to try and MAKE your existing code do what you want, i would just take the list of sections from the linked to post and define what you have and what you want to do for each section (which would become comments in the code). when you get to the point of creating the code for each of those sections, you can reuse some of your existing code.

 

this is the list of those sections, with some specific comments relative to what you are doing -

 

initialization - your head.php file is apparently part of the html page markup? if so, you should require it in the html page/template section.

 

start of database dependent code - you should switch to the PDO api to replace the mysql_ functions. it is more consistent and it is easier to use exceptions with to handle all the database errors than the msyqli_ api.

 

determine user state and permissions - the userid you reference in the code should be from a session variable. there's a comment in your code about it being from a cookie. you should NOT use a cookie to store the user's id. since your code REQUIRES a userid to work, you should make sure there's an id before running any of the code that's dependent on the id value.

 

post method form processing - your form should use method='post' since you are changing data on the server. get requests should be used to control what to display on a page, not to change data.

 

get method business logic - this is the code that retrieves just the data to display the cart. it's the sql statement, running the query, and fetching any/all the rows into a php array variable.

 

end of database dependent code - no comment beyond what is mentioned at the linked to post.

 

get method presentation logic - since you are calculating tax, shipping, and totals (which you can probably do most of in the data retrieval query), you would perform those calculations in this section while you are looping over the contents of the cart and producing the output in a php variable(s).

 

i see that you are using htmlspecialchars() on some values being used in queries and in calculations. htmlspecialchars() is an output function. you use it at the point where you are producing output that goes to the browser. it actually has no effect on the numbers you are using it on and is just cluttering up the code where it is being used that doesn't have anything to do with output to the browser.

 

you are also running a query inside of a loop. you should instead JOIN the postage table in with the cart data retrieval query.

 

html page/template - no comment beyond what is mentioned at the linked to post.

Link to comment
Share on other sites

also, the form that's being produced by the code in this thread doesn't have the ability to insert new items to the cart. it is only adjusting quantities. it only needs to update non-zero quantities and delete any row(s) with a quantity of zero.

 

and the biggest reason why the updating of the quantities isn't working as expected is because your form is foobar.

 

you need to decide if you are going to have one form that updates all the quantities at once or have individual forms for each item in the cart and update the quantity for just that item when the quantity gets changed in the form field.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.