-2

I try to send loop variable to another page with url and GET. but $_GET just only print the last value.

This My code now

 ...
 //example
 $codereg[0] = 6;
 $codereg[1] = 2;
 $codereg[2] = 67;

if ($option =='sent')
{

   foreach($codereg as $ids) 
   {
   header("location:checkout.php?id=$userId&productIds[]=$ids");
   }

}

and this my checkout.php

 <?php
 $userId= $_GET['id'];
 $code= $_GET['productIds'];

 foreach($code as $test)
 {
 echo $test;
 }
 ?>

some one help me fix my code or give better solution...

raregroove
  • 11
  • 1
  • 1
  • 6

2 Answers2

0
foreach($codereg as $ids) 
{
    header("location:checkout.php?id=$userId&productIds[]=$ids");
}

You should have only one header location. It can not be in loop.

You can do like this using delimiter comma:

header("location:checkout.php?id=$userId&productIds=".implode(',', $ids));

And your handler checkout.php:

$userId= $_GET['id'];
$ids = explode(',', $_GET['productIds']);
var_dump($ids);

Use $_GET is not a good idea for products checkout. $_GET can be easy modified and length of url is limited. So count productIds is limited.

You can use $_SESSION instead of $_GET to store productIds.

$_SESSION["productIds"] = $ids;
jekaby
  • 403
  • 3
  • 13
  • what if there are 100 id's ? Implode is a bad option for that. On URL you can pass that much characters. I hope you know that very well – Nehal May 30 '16 at 08:57
  • @Ms.Nehal if there many ids, author should use `$_SESSION` instead of `$_GET`. I only suggested one option how to avoid loop and pass several ids. And yes, `$_SESSION` will be better for checkout.php. – jekaby May 30 '16 at 09:18
  • that is what I'm trying to say. Mention all the options in your answer. Else user's can downvote your answer for a bad option. – Nehal May 30 '16 at 09:22
  • @Ms.Nehal thanks for advice. – jekaby May 30 '16 at 09:36
-1

Do it like this:

$codereg[0] = 6;
$codereg[1] = 2;
$codereg[2] = 67;

if ($option =='sent') {
   header('location:checkout.php?id=$userId&productIds[]=' . implode('&productIds[]=', $codereg));
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50