PHP and MySQL: How to modify a specific item in a multi-product shopping cart?

Hey everyone! I’m building an online store and I’m stuck on the cart update feature. Here’s what I’ve got:

My cart page shows all the items a user has added. Each item has its own form with a quantity box and an update button. I’m trying to send the item ID to my update script when the button is clicked, but it’s not working.

Here’s a simplified version of what I’m doing:

// In cart.php
while ($item = $result->fetch_assoc()) {
  echo "<form action='update.php' method='post'>";
  echo "<input type='number' name='qty' value='1'>";
  echo "<input type='hidden' name='item_id' value='{$item['id']}'>";
  echo "<button type='submit'>Update</button>";
  echo "</form>";
}

// In update.php
$qty = $_POST['qty'];
$item_id = $_POST['item_id'];
$user_id = $_SESSION['user_id'];

$query = "UPDATE cart SET quantity = ? WHERE item_id = ? AND user_id = ?";
// Execute query with prepared statement

Any ideas on what I’m doing wrong or how to fix this? Thanks!

Your approach seems logical, but there might be a few areas to investigate. First, ensure your database connection is properly established in update.php. Next, verify that your prepared statement is correctly executed and that you’re checking for errors. It’s also worth considering implementing AJAX for a smoother user experience - this would allow updates without page reloads. Lastly, don’t forget to validate and sanitize user inputs to prevent potential SQL injection vulnerabilities. If issues persist, examining server logs could provide valuable insights into what’s occurring behind the scenes.

hmm, have u tried debugging to see if the item_id is actually being sent? maybe echo it out in update.php to check? Also, are u sure the form is submitting correctly? Could be worth adding some js to handle the submission and see whats happening. just some thoughts!

hey nova73, i think ur code looks ok, but maybe check if the session is started in update.php? If not, $_SESSION[‘user_id’] might be empty. also, double-check ur database connection in update.php. those are common gotchas. good luck!