This is our beginners guide to PHP Query string url parameters. After completing this lesson you will have a general knowledge of PHP's $GET function with parameters. Let's break down the code in this lesson and see how PHP Query Strings work. Here are the files for this lesson.
What Are Query String Parameters In PHP?
A Query String Parameter is usually associated with a search feature. Think of a query string as a question. Think of the parameter as the operator. Let's illustrate this with a simple example. Here is our question.Php?If we pop this question into Google, Bing or Yahoo you will notice something in the #inbound-link-method-1">URL. Notice at the top in the web address where it reads "search/?q=". This is the start of the query string. The question mark with the letter "q" is the parameter. Our search in this instance only had one query term. "php".
How Do Multi Parameters Work In PHP Query Strings?
Multi parameters take in more that one term. In our example below in the query string there are 3 parameters.- q
- oq
- aqs
How To Get Query String Parameters In PHP
You may be wondering how to get a query string and show it in a page within the HTML. Well, if your parameter is the letter q your URL would look something like this. https://example.com/foo.php?q=foo To get whatever is in the parameter of "q" you would use this php code somewhere on the page.<?php echo $_GET['q']; ?>The print out on the page would look like this, "foo". If you wanted more that one term in your parameter you would separate it in the URL with the plus "+" sign. Here is an example.
https://example.com/foo.php?q=foo+dooThis will print out on the page, "foo doo".
Using Multi Parameters In URL for PHP Query Strings
So there may come a time when you need to set multi parameters in your URLs. You would set up the URL for multi parameters like this.https://example.com/foo.php?q=foo&w=dooTo get those parameters with PHP you would use a code like this.
<?php echo $_GET['q']; echo $_GET['w']; ?>
PHP Error Notice: Undefined index:
The problem with the above codes is that if you do not have the parameters loaded in the URL, PHP will give an error notice of undefined index. In the old days before PHP7 we use to handle that error like this.if(isset($_GET['q'])){echo $_GET['q'];}Now In PHP7 We can write the code like this, this is called the "null coalescing operator (??)" a new feature in Php 7.
<?php echo $_GET['q'] ?? 'not passed'; ?>If there is nothing in the URL parameter it would read, "not passed". However, if you wanted it to show nothing you could write it like this.
<?php echo $_GET['q'] ?? ''; ?>