0

I want to update the product inventory would be glad if you help I could not. My product list array

$_SESSION['item'];
Array ( 
[0] => Array ( [product_id] => 9 [stock] => 20 ) 
[1] => Array ( [product_id] => 8 [stock] => 30 ) 
[2] => Array ( [product_id] => 7 [stock] => 26 ) 
[3] => Array ( [product_id] => 6 [stock] => 42 ) 
)

I do

$product_id = mysql_real_escape_string($_POST['product_id']);
$stock  = mysql_real_escape_string($_POST['stock']);
$found = false;
foreach($_SESSION['item'] as $product){
    if($product_id == $product['product_id']) {
        $found = true;
        break;
    }
}

if($found){
    $_SESSION['item'][$product_id]['stock'] += $stock;
}else{

    // go get new product and add to $_SESSION['item']
}
5
  • 1
    Well and what's the question? Where is an error? What's does not work? Commented May 12, 2014 at 23:49
  • What's the value of $found after the foreach loop? Commented May 12, 2014 at 23:51
  • not update product stock Commented May 12, 2014 at 23:51
  • its not going to work, stock is not a key of product_id i would restructure the array using the product_id as the first level key Commented May 12, 2014 at 23:52
  • $_SESSION['item'] is NOT indexed by product_id! Commented May 12, 2014 at 23:52

1 Answer 1

1

Try this:

$product_id = mysql_real_escape_string($_POST['product_id']);
$stock  = mysql_real_escape_string($_POST['stock']);
$found = false;
foreach($_SESSION['item'] as $index => $product){
    if($product_id == $product['product_id']) {
        $found = true;
        break;
    }
}

if($found){
    $_SESSION['item'][$index]['stock'] += $stock;
}else{
    // go get new product and add to $_SESSION['item']
}

Explain: the $_SESSION['item'] array is not indexed by the product_id. So you have to get and store an index of the current array item in the foreach loop and use it to update of the $_SESSION['item'] array.

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

2 Comments

Great, I'm pleased :) As reward you can vote for my answer and mark it as answer. Thank you.
How points are given :) I'm tossing up arrow says 15 people need more

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.