vozzek Posted December 1, 2007 Share Posted December 1, 2007 Happy Saturday everyone. I'm just getting familiar with the 'foreach' command, and it appears there may be some things you can and cannot do while in such a loop. Please indulge (and educate) me... Below is my update_cart.php file. The form that gets me here passes a qty array (by element cart id) that holds the quantity of each item in the user's shopping cart. For example: qty[116] = 1 Cart id 116 has a quantity of 1 qty[117] = 2 Cart id 117 has a quantity of 2 etc... My php code will update the quantity field of the mySQL database tbl_cart. That's no problem. Here's the code I'm using to do it (special thanks to roopurt18) : <?php foreach($_POST['qty'] as $id => $qty) { $sql = "UPDATE tbl_cart SET ct_qty = $qty WHERE ct_id = $id"; $result = mysql_query($sql) or die(mysql_error()); } ?> Now, on my view_cart page each row (cart_id) has a convenient REMOVE button that calls another php script to delete it from the database. This works fine also. But somewhere along the line, some Dougie will invariably try to try to update their cart with a quantity of zero (instead of using my convenient button). So when the click the update_cart button and their quantity is zero, I'd like to delete the row (ct_id) from my database. Therefore, I added the following code INSIDE of the foreach loop: <?php foreach($_POST['qty'] as $id => $qty) { if ($qty > 0) { $sql = "UPDATE tbl_cart SET ct_qty = $qty WHERE ct_id = $id"; } else { $sql = "DELETE FROM tbl_cart WHERE ct_id = $id"; } $result = mysql_query($sql) or die(mysql_error()); } ?> For some reason, this is causing every quantity of every item in the cart to be set to zero. I think the problem is foreach loop. Why isn't this working? Thanks in advance. Quote Link to comment Share on other sites More sharing options...
wsantos Posted December 1, 2007 Share Posted December 1, 2007 I know this might be a little wierd for you. But based on your problem description can you run this. <?php foreach($_POST['qty'] as $id => $qty) { if ($qty > 0) { echo "it is greater than zero"; } else { echo "it is equal to zero"; } $result = mysql_query($sql) or die(mysql_error()); } ?> Quote Link to comment Share on other sites More sharing options...
vozzek Posted December 4, 2007 Author Share Posted December 4, 2007 Nope, that's not working either. Is there a problem with my syntax? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.