Create url from dropdown lists?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
KidCactus
Forum Newbie
Posts: 2
Joined: Fri Mar 11, 2011 4:17 pm

Create url from dropdown lists?

Post by KidCactus »

I would like some help with creating an URL from what is chosen in two dropdown lists. Example:

I choose abcd in one dropdown list. Then I choose qwerty from the second dropdown list. When I hit submit, I want to be redirected to http://mysite.com/example.php?arg1=abcd&arg2=qwerty

I assume this is quite easy to do, but I'm new to PHP and I just can't figure out how to do it. :?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Create url from dropdown lists?

Post by John Cartwright »

Since I don't want to do ALL the work for you, here are the basic steps to achieving what you want. In semi-pseudo:

Code: Select all

//check if we have values from our dropdowns 
if() + !empty()  

+

//populate key/value pair for query
$queryargs = array(
   'arg1' => $_POST['your_first_dropdown'],
   'arg2' => $_POST['your_second_dropdown']
);

+

//create our query string with the above array
http_build_query() 

+

//create your $url variable with the domain and the query string, and issue a redirect
header('Location: '. $url);
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Create url from dropdown lists?

Post by John Cartwright »

Alternatively, you could just name the dropdown's arg1 and arg2 respectively, set the form method to GET, and point the form action to the domain/path you want, and it will basically achieve the exact same result (but you won't have control to validate the request server side).

Code: Select all

<form action="http://domain.com" action="GET">
   <select name="arg1">
      <option value="abcd">abcd</option>
   </select>
   <select name="arg2">
      <option value="qwerty">qwerty</option>
   </select>
</form>
KidCactus
Forum Newbie
Posts: 2
Joined: Fri Mar 11, 2011 4:17 pm

Re: Create url from dropdown lists?

Post by KidCactus »

Thanks a lot, that works exactly like I want it to. :)

That second alternative is what I have been trying to accomplish, but I had POST instead of GET.
Post Reply