views:

246

answers:

1

I am using paypal to process payments on my site. Paypal returns the post array like

[item_number1] =12
[item_name1] = My product name
[quantity1] =3
[item_number2] =14
[item_name2] = My product name2
[quantity2] =5
[num_cart_items] 2

Insert step here now im just going in circles getting nowhere

And then run the for loop

for($i = 1;$i <= $num_cart_items ;$i++){
  $x = 'item_number' . $i;
  $y = 'item_name' . $i;
  $z = 'quantity' . $i;


  $new_amount = $row['stock_quantity'] - $$z;
  $db->update1_by_match('cart_products','stock_quantity',$new_amount,'id',$$x);

 }

Im having trouble with these variable variables. Is there a better way to do this?

Thanks Andrew

+7  A: 

I'd change your revised code to use $_POST directly, e.g.

for($i = 1;$i <= $_POST['num_cart_items'] ;$i++){

   $item_number= intval($_POST['item_number' . $i]);
   $item_quantity= intval($_POST['quantity' . $i]);

   printf("DEBUG: item %d item:%d quantity:%d<br>", $i, $item_number, $item_quantity);

   $new_amount = $row['stock_quantity'] - $item_quantity;
   $db->update1_by_match('cart_products','stock_quantity',$new_amount,'id', $item_number);

}

The diagnostic output should help you refine where things are going for you.

EARLIER QUESTION - notes below refer to the question before a complete revision of it was it made.

What you really need is an array, rather than attempting to use variable variables

$item_numbers=array(24, 16);

foreach ($item_numbers as $item_number) {
    $result = $db->get_cols_by_match('cart_products','stock_quantity','id', $item_number);
}

To do it the way you were doing it, something like this might clarify it

$item_number1='24';
$item_number2='16';
$num_cart_items = 2

for($i = 1;$i <= $num_cart_items ;$i++){                
    $varname='item_number' . $i;
    printf("DEBUG: %s = %s<br>", $varname, $$varname);

    $result = $db->get_cols_by_match('cart_products','stock_quantity','id', $$varname);
}

The $$varname is an example of a variable variable, but in your case an array declares your intent in a much clearer way.

Paul Dixon
Shouldn't it be `$varname="item_number" . $i;`?
Tomas Markauskas
Yes, just spotted that - corrected
Paul Dixon
I had simplified the question. The item_number1 and item_number2 came from paypal so i had no control over that. The second way you suggested is what i need, it's obvious, i should go to bed
andrew
That doesn't work. there is something slightly wrong with that i think
andrew
Then the problem probably lies deeper, inside get_cols_by_matchI will amend the code with a diagnostic output to "prove" the approach is at least getting the values out of those variables.
Paul Dixon
Thanks for that i will give it a go tomorrow and see if it works
andrew