1

Let's say my URL is the following:

https://www.example.com/downloads?query=RobinHood

In my template (.phtml file), I have the following input:

<input type="text" placeholder="Query for books" name="query">

What I want to do is check if the URL parameter called query actually exists, and if it does, I want to put it as the value for the input.

How can I do this? Thanks for any help.

darkhorse
  • 8,192
  • 21
  • 72
  • 148

2 Answers2

1

Since .phtml is an extension used for php2, here's what the docs say:

Any component of the GET data (the data following a '?' in the URL) which is of the form, word=something will define the variable $word to contain the value something. Even if the data is not of this form, it can be accessed with the $argv built-in array

So based on this, php2 will automatically create variables for the GET data:

https://www.example.com/downloads?query=RobinHood

$query    // should contain "RobinHood"
$argv[0]  // should contain "query=RobinHood"

To check if a variable has been set you can use IsSet() function:

The IsSet function returns 1 if the given variable is defined, and 0 if it isn't.

if( IsSet($query) )
{
    //...
}

Note: All of the above is purely based on docs. I haven't tested this.

Ivan86
  • 5,695
  • 2
  • 14
  • 30
  • I really doubt someone's actually using PHP v2 in 2021. – ceejayoz Mar 17 '21 at 22:29
  • @ceejayoz Me too, but from [here](https://stackoverflow.com/a/11859122/8202589) and a few other sources it seems to be attributed to php2. I'm not sure if the extension can be used in later versions of PHP and how it behaves. – Ivan86 Mar 17 '21 at 22:32
  • I think the more likely explanation is someone's just using `.phtml` either for very very very legacy reasons (old URLs) or an affectation/anachronism. – ceejayoz Mar 17 '21 at 22:34
  • @ceejayoz I agree, that's very likely the case. Curious to see what the OP will answer to your question about the version in the comments. – Ivan86 Mar 17 '21 at 22:39
  • 1
    I guess it is a legacy system actually. – darkhorse Mar 18 '21 at 06:35
  • @darkhorse Yikes! – ceejayoz Mar 18 '21 at 12:05
0

You can check the query parameter from $_GET variable:

<input type="text" placeholder="Query for books" name="query" <?php echo isset($_GET['query']) ? '"value"="'.$_GET['query'].'"' : '' ?>>
Amir MB
  • 3,233
  • 2
  • 10
  • 16