Help - Search - Members - Calendar
Full Version: Query Strings
Forums > Resource Center > Webmasters' Corner > Webmasters' Corner Resolved Topics
Mikeplyts
I was wondering how you could make those url's that have a question mark and a few equal signs and such at the end of a url. I belive they are called query strings, right? How can I do it to like make a page go to a next page such as this where it has "?page=2". I know it has to something with PHP and I tried googling tutorials but I just don't understand. Can someone please explain how to do this like if I wanted to make the page go the second page using a simple HTML "a" tag? Thanks. _smile.gif
mipadi
Like this:

CODE
<a href="/path/to/page.php?page=2">Page 2</a>


Of course, query strings are useless unless you have some PHP code to extract and use the values in the query string. You can do this using PHP's $_GET variable:

CODE
<?php echo $_GET["page"]; ?>
Mikeplyts
Oh ok. Also, would I have to make a new page that's called "2" or something?
mipadi
No, the script that gets run would be whatever's in the path, e.g., page.php in the above example. So page.php?page=1 and page.php?page=99 are all handled by page.php, which would contain the logic for working with the query string values.

My personal website uses a page parameter in the query string to handle paging, as seen here. It's written in Python, so it may not help you understand, but here's the snippet of code I use to handle page numbers:

CODE
def get_page(request):
    try:
        # Grabs the page from the query string
        page = int(request.GET['page'])
    except ValueError:
        raise PageError
    except KeyError:
        # If there's no ?page attribute, we want to
        # show the first page of results
        page = 1
    
    if page < 1:
        raise PageError
    return page


def index(request):
    try:
        page = get_page(request)
        return render_to_response("blog/paged.html", get_posts(page))
    except PageError:
        return HttpResponseRedirect(reverse('blog'))
newkidontheblock
I know the code above is too advance for someone who is a beginner but here is a simply code. The code is mostly self explanatory.

CODE
<?php
    if ( isset( $_GET['page'] ) ){
        $page = $_GET['page']; # Getting page ID ex. ?page=2
    }
    if ( empty( $page ) || $page == '' || $page == '0' ){
        echo "Home Page Content";
    } else if ( $page == '1' ){
        echo "Page 1 Content Goes Here";
    } else if ( $page == '2' ){
        echo "Page 2 Content Goes Here";
    } else {
        echo "Page Not Found";
    }    
?>


Within the code their are for pages:
- Homepage
- Page 1
- Page 2
- Error Page

To access the Homepage you simply can access it by going to the page.php, or page.php?page=0
To access page one and to you can go to page.php?page=1 or page.php?page=2
To acess the error page you can go to any page that is not listed ex. 3, 4, 5, etc.

To add new page you can add an
CODE
else if( $page == 'PAGEID') {
    echo "Page content goes here";
}

Make sure it is places before the else statement.
PAGEID Doesn't have to be a number it can be letters too.

HERE is a preview
Mikeplyts
^Ok, I tried it but it still wasn't working for me. It shows the page blank. I notice you have a script tag that has a src of "./js/jquery.js". Do I have to make a .js page to put the php in? Also, should I add the DOCTYPE?
Maccabee
Or! If it's in the case of a form or something, it would be like this page:
http://wefuze.com/php/form.php
Because i used get on the form it shows the php results in the address bar which allows someone to bookmark it.
Edit: I o see you wanna know about doctypes too. yes its good to add one.
At the top of the page add:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

After much researcher I have learnt that on any page this is prob the best to use.

And replace <html> at the top with:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
Mikeplyts
Ok, I figured out how to make it not be blank but would I be able to put HTML tags into the 'echo' property in Fawaz's code?
mipadi
QUOTE(Mikeplyts @ Feb 22 2009, 06:44 PM) *
Ok, I figured out how to make it not be blank but would I be able to put HTML tags into the 'echo' property in Fawaz's code?

Yes.
Mikeplyts
Could I also put PHP includes in there?
Maccabee
Yes. But dont put <?php include() ?> just put include() cause the <?php ?> tags are already there. Unless of course you put it outside the code then it would be normal.

Edi: also quick thing, even though long php url's look cool, it's not very practical and it would be better to keep em short.

What i do is make a seperate directory with its own index for each new page so instead of wefuze.com/contact.php its wefuze.com/contact/
mipadi
QUOTE(Mikeplyts @ Feb 22 2009, 06:57 PM) *
Could I also put PHP includes in there?

Yes. You can put in any PHP code you want.

However, you really should ask yourself why you're using the query string. If you're using it for, e.g., pagination in a blog, then good. But don't use the query string to specify wildly different pages (i.e., don't do something like "index.php?page=main", "index.php?page=about", etc. -- in other words, don't make one big "index.php" file that handles your entire site).
Mikeplyts
Ok. Thanks. biggrin.gif Another question, how I could make the double quote ( " ) appear inside the echo property without making the code mess up?
newkidontheblock
Use forward slash \ before any Quotes like \"
mipadi
You have to escape them with a backslash \, like so:
CODE
<?php echo "\"What string?\" he asked."; ?>

Or you can use single quotes around the string:
CODE
<?php echo '"What string?\" he asked."; ?>

The second method has a few gotchas, though:
  • You'll now have to escape apostrophes '.
  • Variable interpolation does not work in single-quoted strings.
newkidontheblock
Here is an easy way to do use HTML inside in those parameters that I provided
CODE
<?php
    if ( isset( $_GET['page'] ) ){
        $page = $_GET['page']; # Getting page ID ex. ?page=2
    }
    if ( empty( $page ) || $page == '' || $page == '0' ){
        echo "Home Page Content";
    } else if ( $page == '1' ){
        echo "Page 1 Content Goes Here";
    } else if ( $page == '2' ){
        echo "Page 2 Content Goes Here";
    } else {
        echo "Page Not Found";
    }    
?>


Just close off the PHP after the opening parentheses like this.
CODE
else if ( $page == '1' ){ ?>
ANY HTML CODE HERE
<?php } ?>
and reopen it before the closing parentheses.
Mikeplyts
Thanks. biggrin.gif

One more question, how could you add another "variable"? Like "?NAME=VALUE&ANOTHERNAME=ANOTHERVALUE".
mipadi
QUOTE(Mikeplyts @ Mar 13 2009, 05:19 PM) *
One more question, how could you add another "variable"? Like "?NAME=VALUE&ANOTHERNAME=ANOTHERVALUE".

Just make a link:

HTML
<a href="?name=value&amp;anothername=anothervalue">Links</a>


Different values are separated by an "&".
Mikeplyts
^Yeah, I know that but how do I like 'define' it in the PHP code?
mipadi
QUOTE(Mikeplyts @ Mar 13 2009, 06:11 PM) *
^Yeah, I know that but how do I like 'define' it in the PHP code?

Access it with the $_GET variable:
CODE
$var = $_GET['name'];
$other_var = $_GET['anothername'];
Mikeplyts
^And how would I add that to Fawaz's code?

Thanks for the help btw..:p
mipadi
QUOTE(Mikeplyts @ Mar 13 2009, 07:04 PM) *
^And how would I add that to Fawaz's code?

Thanks for the help btw..:p

Depends on where you want to use it, and what you want to do with it.

The simple answer is, "Anywhere you want to."
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.