How to capture (GET) multiple values sent in the same variable (PHP)?

0

After a query, I am sending different values through the same variable (via an input):

 <input type="hidden" id="sku" name="sku" value="<?= $reg->sku ?>"> 

That way, my URL looks like this:

http://localhost/admin/anuncios/relatorios/exportado_confirm.php?sku=BL001_BA307&sku=BL001_BA308&sku=BL001_BA667&sku=BL001_BA668&sku=BL001_BA672&sku=BL003_BA309&sku=BL005_BA27&sku=BL166_BA7&sku=BL166_BA8&sku=BL178_BA310&sku=BL184_BA1&sku=BL184_BA4&sku=BL184_BA669&sku=BL202_BA5

But I can not capture all the sku sent through $sku = $_GET['sku']);

For when I run the following UPDATE : $sql = "update anuncios set exportado = '1' where sku = '{$sku}'";

It can only catch the last value sent in the variable "sku" and run the UPDATE on the last "sku" listed in the URL.

I wanted to be able to capture all the values, and that UPDATE (while) while there was some value in the variable sku. Anyone have any suggestions to help me?

Note: I'm actually doing everything by POST, I just put it by GET to be visible the values sent in the same variable.

    
asked by anonymous 21.09.2017 / 15:53

1 answer

4

The official URL structure is defined by RFC 2986 , with Session 3.4 addressing the query definition and even in it there is no "official" way to pass multiple values to the same parameter. Since query is an opaque value - that is, its actual meaning depends on the implementation that will parse the URL, the way to pass multiple values will vary.

In PHP, the brackets are officially used after the field name:

<input type="hidden" id="sku" name="sku[]" value="BL001_BA307"> 
<input type="hidden" id="sku" name="sku[]" value="BL001_BA308"> 
<input type="hidden" id="sku" name="sku[]" value="BL001_BA667"> 

This will generate a URL similar to:

//localhost?sku[]=BL001_BA307&sku[]=BL001_BA308&sku[]=BL001_BA667

And PHP, when parsing it, will generate an array with this information:

var_dump($_GET["sku"]);

array(3) {
  [0]=>
  string(11) "BL001_BA307"
  [1]=>
  string(11) "BL001_BA308"
  [2]=>
  string(11) "BL001_BA667"
}

So you can use all the information next to SQL, remembering that it should be properly converted to string before using it in the SQL query.

This technique will work for both GET and POST requests. The only difference, in fact, between them will be the form that the values will be passed via HTTP request: in GET it is via URL and in POST it is via request body.

As in the SQL query, the desired result is something like:

select ... where sku in ("BL001_BA307", "BL001_BA308", "BL001_BA667");

What you can do is to use implode of PHP:

$sku = implode(",", array_map(function ($item) {
    return sprintf('"%s"', $item);
}, $_GET["sku"]));

// $sku = '"BL001_BA307", "BL001_BA308", "BL001_BA667"';

And in SQL:

select ... where sku in ({$sku});
    
21.09.2017 / 18:50