0

I've got one nagging little bug in this script. I'm going through my cart items and passing them into hidden inputs. The cart_id ($obj->id) is working fine into the value="" but my iteration loop that gives each value a unique name="" (cart_id_1, cart_id_2 etc) is NOT iterating.

<?php         

           $pass_cart_q = "SELECT c.id FROM carts AS c WHERE c.user_session_id='$sid'";
           $result = $mysqli->query($pass_cart_q);

                    $i = 1; 
                while ($obj = $result->fetch_object()) {

                    echo "<input type=\"hidden\" name=\"cart_id_".$i."\" value=\"  .$obj->id.  \"><br>";  
                    $i = $i++;
                }
                mysqli_close();?>

Each name field is coming through as cart_id_1

1
  • I've just found the thread that states you can cast a hidden field into an array using square brackets - name="name[]" ... I was operating on the assumption that I would be overwriting the values, but I will see if this works. Commented Aug 19, 2011 at 10:20

4 Answers 4

2
$i=$i++;

That's the problem just do:

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

Comments

2

Please replace $i = $i++; with just $i++.

$i = 1;
$i = $i++;

echo $i, "\n"; // 1

$i = 1;
$i = ++$i;

echo $i, "\n"; // 2

$i = 1;
$i++;

echo $i, "\n"; // 2

$i = 1;
++$i;

echo $i, "\n"; // 2

2 Comments

The increment operator VAR++ returns the value of VAR and afterwards increasing the value of VAR by one. You may simply use VAR++ as suggested or VAR = ++VAR, to get the already increased value.
Yes! The interesting thing is with $i = $i++ that after assigning the value of the right $i to the left $i the incrementor does not operate on our left $i. There are at that time apparently two different references for the same variable name.
0

What $i = $i++ will cause it literally this: "make $i equal to $i and then increase it by one", but the $i will still remain the same. To solve this, simply replace $i = $i++; with $i++.

Manual Entry

1 Comment

Why the $i will still remain the same?
0

you are assigning the incremented value to $i variable. and hence it is not able to iterate. instead you should remove that assignment variable $i and it should only be $i++

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.