1

php

if(isset($_SESSION["basket_array"])){
    foreach($_SESSION["basket_array"] as $each_item){

        (mysql_query("UPDATE book SET copies=copies-1 WHERE bookid='$bookid'");

    }
    unset($_SESSION["basket_array"]);
    header( 'Location: account.php' ) ;
}

Shopping Cart Update Stock I am updating my database using this php code. It is activated on button click. It takes the items in basket_array and using the $bookid it is meant to deduct 1 from the copies left in the database. But it only deducts from the last item in the array. e.g if there are 12 items in the basket it take twelve copies from last item in the basket. Thanks for the help. Ask me for more info if concept is not grasped.

Session Output $_SESSION["basket_array"]

array(2) { 

[0]=> array(1) { 
["bookid"]=> string(1) "1" 
} 

[1]=> array(1) 
{ ["bookid"]=> string(1) "6" 
} 
}
4
  • 2
    You need to change the value of $bookid inside your loop. Commented Mar 20, 2014 at 17:43
  • Also - you're setting '$each_item in your loop, but then using $bookid in your query. There's no way for someone to help fix this without knowing what the contents of $_SESSION["basket_array"] are. Commented Mar 20, 2014 at 17:54
  • @andrewsi thats what is stored in the array Commented Mar 20, 2014 at 18:13
  • 1
    Then I think you need to set $bookid = $each_item['bookid'] as the first line inside your loop. Commented Mar 20, 2014 at 18:15

1 Answer 1

1
foreach($_SESSION["basket_array"] as $each_item){
    (mysql_query("UPDATE book SET copies=copies-1 WHERE bookid='$bookid'");
}

You're not setting $bookid inside your query, so every time the query runs, it's updating the same row. You need to change that as you iterate through the loop:

foreach($_SESSION["basket_array"] as $each_item){
    $bookid = $each_item['bookid'];
    (mysql_query("UPDATE book SET copies=copies-1 WHERE bookid='$bookid'");
}

A couple of other things you might want to consider - you're not checking that your query actually worked, so if there's an issue with the connection, you'll never know about it.

You might also want to look at switching to PDO or mysqli_ functions. They both let you use prepared statements. They will help you write more secure code, and in a case like this, where you're running the same statement several times in a loop, they'll do it more efficiently, too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.