PHP and mySql — Help with retrieving query terms from a url?

Question by ~*Stephanie S: PHP and mySql — Help with retrieving query terms from a url?
I am using PHP and mySql to build a page that users can use to search a recipe database. The search part of the page works fine– now, I’m trying to create a page called displayrecipe that will display whatever recipe the user selects. A snippet of my code is:

$ encodedRecipeName = urlencode($ recipeName);
echo ” $ recipeName “;

The above code creates links similar to the one below (grilled chicken salad is just an example… it could be ANY recipe name in the database):
displayrecipe? grilled+chicken+salad

What code do I need on my displayrecipe page to retrieve the “grilled+chicken+salad” part of the url (preferably without the +’s)?

(I’ll add more details if need be… please just ask)

Best answer:

Answer by tutejasaurabh
First suggestion would be to change your html code to something of the sort :
$ encodedRecipeName = urlencode($ recipeName);
echo “ $ recipeName “;

Thus, you can access the query string from the variable `q` directly by using $ q (if register_globals is set to On) or from some of the global arrays. This variable will have these values as space seperated, so u can just explode on ” ” to get the list.

But, if for whatever reasons you are unable to do the above, you can try to explore $ GLOBALS or $ _SERVER variable(by print_r($ _SERVER)), here u will be able to find quite a few other ways of accessing the values.

Know better? Leave your own answer in the comments!

Revisions

There are no revisions for this post.

Tags: , , , , ,

One Response to “PHP and mySql — Help with retrieving query terms from a url?”

  1. NC October 16, 2011 at 9:23 PM #

    First off, change your snippet like so:

    $ encodedRecipeName = rawurlencode($ recipeName);
    echo “ $ recipeName “;

    (Replace urlencode() with rawurlencode(), replace the backward slash with a forward slash, add quotes around the hyperlink, and get rid of the space after the question mark.)

    Then, inside displayrecipe, you can write:

    $ query = rawurldecode($ _SERVER[‘QUERY_STRING’]);

    which will set your $ query to “griled chicken salad”.

    A more common way of doing this, however, would be:

    $ encodedRecipeName = rawurlencode($ recipeName);
    echo “ $ recipeName “;

    Then, the recipe name will be accessible as $ _GET[‘name’].

Leave a Reply