billy_111 Posted May 23, 2010 Share Posted May 23, 2010 Hey, I am trying to update a table based on values from a session array in a shopping basket. When i add to cart i have the following method: public function AddToCart(){ !isset($_SESSION['ID']) ? $_SESSION['ID'] = array() : ''; !isset($_SESSION['theName']) ? $_SESSION['theName'] = array() : ''; !isset($_SESSION['quantity']) ? $_SESSION['quantity'] = array() : ''; !isset($_SESSION['price']) ? $_SESSION['price'] = array() : ''; !isset($_SESSION['image']) ? $_SESSION['image'] = array() : ''; array_push($_SESSION['ID'], $_POST['ID']); array_push($_SESSION['theName'], $_POST['theName']); array_push($_SESSION['quantity'], $_POST['quantity']); array_push($_SESSION['price'], $_POST['price']); array_push($_SESSION['image'], $_POST['image']); $loc = $_SERVER['HTTP_REFERER']; echo "<script>window.location.href='".$loc."'</script>"; } Now when someone confirms an order i need to update the stock list to mange the stock control. Therefore i need to update the stock value based on the quantities of the items in the basket. So i tried doing this: public function deductQuantitiesFromItems(){ $i=0; session_start(); foreach($_SESSION['ID'] as $ID): $sql = 'UPDATE hussaini_items SET stock = stock - '.$_SESSION['quantity'][$i].' WHERE ID = '.$ID; $result = $this->mysqli->query($sql) or die($this->mysqli->query($sql)); return $result; $i++; endforeach; } I get this error: Warning: Invalid argument supplied for foreach() in G:\xampp\htdocs\Manstore\Models\Cart.class.php on line 121 Why doesn't the update work? Thanks again Link to comment https://forums.phpfreaks.com/topic/202665-for-loop-in-session-array-in-update-sql-statement/ Share on other sites More sharing options...
kenrbnsn Posted May 23, 2010 Share Posted May 23, 2010 When you do this: <?php !isset($_SESSION['ID']) ? $_SESSION['ID'] = array() : ''; ?> and $_SESSION['ID'] is already set, you're making it the null string (which is not an array). This is where a plain "if" would be better: <?php if (!isset($_SESSION['ID'])) { $_SESSION['ID'] = array(); } ?> Ken Link to comment https://forums.phpfreaks.com/topic/202665-for-loop-in-session-array-in-update-sql-statement/#findComment-1062367 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.