Shay Young
Shay Young

Reputation: 207

updating database from session array data

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" 
} 
}

Upvotes: 1

Views: 66

Answers (1)

andrewsi
andrewsi

Reputation: 10732

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.

Upvotes: 1

Related Questions