Pass parameters via GET and include more parameters

Asked

Viewed 11,114 times

2

I have a consultation page, where several parameters can be included in this query. I would like to concatenate more parameters if there are already parameters in that query. In short, take the parameters that already exist and concatenate if the user chooses any more.

Ex: <a href="?sexo=m">Masculino</a> <a href="?cor=verde">Verde</a>

  • Is the link mounted only with html? The second parameter and the others are separated by &

  • Yes, but then I would have to do ? sex=m&cor=green

  • Good evening, I wonder if the answer helped you, if not please comment on what you think is missing.

2 answers

2

If query came by GET at an address similar to this:

http://site/page.php?b=1&c=2

And you want the link <a href="?cor=verde">Verde</a> receive together b=1&c=2, you can use $_SERVER['QUERY_STRING'].

For example:

<?php
//cria a variavel vazia
$qs = '';

//Verifica se QueryString é vazio, se não for então seta a variavel $qs
if (false === empty($_SERVER['QUERY_STRING'])) {
   //O & no final é para separar as variaveis
   $qs = $_SERVER['QUERY_STRING'] . '&';
}
?>

<a href="?<?php echo $qs; ?>cor=verde">Verde</a>

To avoid repeated values, you can use an array using parse_str and http_build_query:

<?php
$qs = '';

if (false === empty($_SERVER['QUERY_STRING'])) {
   $qs = $_SERVER['QUERY_STRING'] . '&';
}

//extrai a querystring para uma array/vetor
parse_str($qs, $output);

//Exibe o resultado
print_r($output);
?>

<?php
//Copia o output para não misturar os links
$link1 = $output;

//Cria o seu link com o valor cor=verde
$link1['cor'] = 'verde';
?>
<a href="?<?php echo http_build_query($link1); ?>"></a>

<?php
//Copia o output para não misturar os links
$link2 = $output;

//Cria o seu link com o valor sexo=m
$link2['sexo'] = 'm';
?>
<a href="?<?php echo http_build_query($link2); ?>"></a>

This will prevent something like:

?cor=verde&cor=verde

So first the user chooses cor=verde and the url goes like this:

./page.php?cor=verde

So he chooses sexo=m and the url goes like this:

./page.php?cor=verde&sexo=m
  • has some errors, at first it would be the function Empty is not?

  • I do not have much experience in ternary operators, could explain what would be Empty($_SERVER['QUERY_STRING']) ? '' ($_SERVER['QUERY_STRING'] . '&');

  • @Mateuscarvalho I edited the answer and added some comments to facilitate and fix an error in ifs.

0

Use the & at the beginning of a new parameter.

   ....
    <a href="?sexo=m&cor=verde">Masculino e Verde</a>
    ....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.