PHP Dynamic Dropdown Selection

I am pretty new to PHP.  I have created a simple member site and after a user logs in, they will come to a page where they set a destination that comes from a drop-down selection being populated from a MySQL table.

In other portions of my site I am using URL parameters to affects forms I have built and these work fine.  Those involve static data from the user registration.

My is that the destination selection can be any one of dozens of selections.  Ideally, when the user is presented with the page, they will make a selection from the drop-down and the URL will automatically be updated with additional parameters (the URL will already include parameters from their logging in) based upon their selection.  The user may change their selection while on the page and the URL should obviously reflect the new selection.

I am open to other ways of doing this.

      // declare database connection variables.
      $host = "mysql"; // host name
      $username = "batemanweb"; // mysql username
      $password = "john1234"; // mysql password
      $db_name = "Bookings"; // database name
      $tbl_name = "Stores"; // table name

      // connect to server and select database.
      mysql_connect("$host", "$username", "$password")or die("cannot connect");
      mysql_select_db("$db_name")or die("cannot select DB");

      // mysql query that retrieves data from one column from a table, ie names.
      $sql = "SELECT CONCAT(company, ' - ',city, ', ',state) as CoCiSt, id, company, FirstName, LastName, Email, phone, cell, Address, City, State, Zip FROM $tbl_name ORDER BY company ASC";

      $result = mysql_query($sql) or die(mysql_error());
      // declare dropdown variable.            

      $dropdown = "<select name='items' class='select'>";

      // start loop; as long as there is data in the column.
      while ($row = mysql_fetch_assoc($result)) {
            $stid = $row['id'];
            $stcompany = $row['company'];
            $stfirstname = $row['FirstName'];
            $stlastname = $row['LastName'];
            $stemail = $row['Email'];
            $stphone = $row['phone'];
            $stcell = $row['cell'];
            $staddress = $row['Address'];
            $stcity = $row['City'];
            $ststate = $row['State'];
            $stzip = $row['Zip'];
            $dropdown .= "\r\n<option value='{$row['CoCiSt']}'>{$row['CoCiSt']}</option>";
        $selected = "selected='selected'";            

            header("Location: ../Forms/Bookings/Bookings.php?FirstName=$stfirstname&LastName=$stlastnme&userid=$stid&Address=$staddress&City=$stcity&State=$ststate&Zip=$stzip&Email=$stemail&HomePhone=$stphone&MobilePhone=$stcell");
      $dropdown .= "\r\n</select>";

      // display dropdown.
      echo $dropdown;
      echo "Testing";
      echo $City;

Who is Participating?
Ray PaseurCommented:
Did you try running the script here?  It simulates many of the pieces that are needed to get you closer to a workable answer.  There really are a lot of moving parts to your question!  You will need working knowledge of PHP, MySQLi, HTML, and possibly CSS.  It's not possible to eat the elephant all at once, but you can start one bite at a time. :-)

After your script has run a query, there is a results set available on the MySQL server.  Your script can access this with one of the fetch_object() methods.  As you fetch each row, you can add the data to an array.  Once your script has all of the data in the array, you can use it to generate the HTML select/options (See the $dat variable in the code example above).

Getting started in PHP is usually easier if you have some dependable learning examples.  There is an awful lot of bad code lying about on the internet.  This article helps sort out the wheat from the chaff.  Any of the books mentioned will teach all of the various parts that are needed to answer your questions here.  The answers will span chapters, so prepare yourself for a learning exercise and take your time.

Best regards, and best of luck with your project, ~Ray
You could use $_SESSION to save the user info instead "redirect"

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
dalerbrumbaughAuthor Commented:
Thank you for the suggestion.  Being new to PHP, any actual renditions to the code I posted would be most helpful.

To be clearer, my biggest problem is that when a user makes a selection, nothing happens.  I am not familiar enough with PHP yet to determine how to detect the selection and use the values.
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

You have to refresh the page to get the selected values.

<form action="yourpage.php" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>

Open in new window

Then if you print the var $_POST

like var_dump($_POST) you will see in second refresh that Post var will have the values you want.

If you want to print values without going to server again you do that only with javascript ( client side )
Robert SaylorSenior DeveloperCommented:
I would use a GET if you are not sending a lot of data. That way if the user presses the browser back button they won't get that funky message from the browser and resubmitting post data...

put this in your code for debug so you can see the posted or get data:

For GET Data:

foreach ($_GET as $key=>$value) {
   print "Key: $key | Value: $value<br>\n";

Open in new window

For POST it's the same just replace GET with POST
dalerbrumbaughAuthor Commented:
Thanks for the input thus far.  As I mentioned I am new to PHP (used another tutorial to create the member login section I referenced before) so without seeing the suggestions relative to the code I posted, I end up  trying a lot of combinations of what I "think" you mean.  Obviously I am not figuring it out despite your suggestions.
Robert SaylorSenior DeveloperCommented:
I would suggest reading up on sessions. What are you using for your member login? A database to store there details and login data?
dalerbrumbaughAuthor Commented:
Thanks, I am reading up on sessions from the first link.  For the member login I am using a MySQL database to store their information and login data.
You want to know what is the user choice right? But when he pick a select the server have no info about that, thats why you have to make a submit ( post or get ) and then the server will see them populated in $_GET or $_POST var.

Just use print() or var_dump() to help you displaying the values on screen.

Before submit are all empty and after submit they will store the values inside the submit form.
dalerbrumbaughAuthor Commented:
Correct, I want to know the user choice.  Perhaps my understanding is not correct; in my example code I am under the impression that I have loaded all of the table information already client side (thus the list for selection in the dropdown).  Does this actually require server activity to determine what is selected?
Ray PaseurCommented:
There are a lot of moving parts to this question and maybe some of them are handled in the PHP introductory tutorial.  CF "Dealing with Forms."

GET method requests are appropriate when the request does not change state/data on the server.  POST requests are required for changes.  You would make your action= attribute reflect the desired request method.

Here is an example that simulates a DB query to set up a GET request.  Install it, run it, and try a few different experiments with it.  You will be able to see the URL change, and you will be able to see, via var_dump(), what is contained in the $_GET request array.

<?php // RAY_temp_dalerbrumbaugh.php

// SEE

if (!empty($_GET['color'][0]))
    echo '<pre>';
    echo '</pre>';
    echo PHP_EOL;

$dat = array
( 'red'
, 'green'
, 'blue'

$opts = '<option value="" selected>Choose Color(s)</option>' . PHP_EOL;
foreach ($dat as $opt)
    $opts .= '<option value="' . $opt . '">' . $opt . '</option>' . PHP_EOL;

$htm = <<<EOD
<form method="get">
<select name="color[]" multiple>
<input type="submit" />

echo $htm;

Open in new window

dalerbrumbaughAuthor Commented:
Thanks Ray_Paseur, this is making sense.
As I work with this a question that immediately arises is how to I load my sql query results into the array?
Ray PaseurCommented:
Please correct an error in my earlier post.  This is wrong:

You would make your action= attribute...

This is what it should have said:

You would make your method= attribute...

If you're new to PHP and MySQL, this book will help a lot.

When you use the MySQLi extension, you must fetch all of the rows and build the array with the information in each row.  You would do this with an iterator like while() that lets you access each row of the results set.   When you use the PDO extension, there is an option to retrieve all of the rows at once. The result is an array of arrays or an array of objects.  In either case, once you've retrieved all the rows, you use an iterator like foreach() to access the data elements.  Examples showing how this is done are given in this article.  It's primarily about why we cannot continue to use MySQL, but if you read the code examples, you will probably find the answers.

Once you've read the code examples in the article, please post back if you still have questions.  Best regards, ~Ray
dalerbrumbaughAuthor Commented:
Ok Ray,
I am still reading and testing.  As is probably true with most who post here I have a real world problem I am trying to solve and my limited knowledge is hindering me.  I will keep working through this.
If anyone can post an example of the following it would be very helpful:

- build dropdown selection from SELECT statement of MYSQL table
- when user selects option in dropdown, the URL is modified to reflect parameters from query
- if user changes the selection the URL changes also

If I get a good example of this I am sure I can quickly proceed and continue my knowledge.
Thanks to all
dalerbrumbaughAuthor Commented:
The only reason why I didn't grade this as excellent is that in posting my code I hoped to get suggestions as to how to actually modify it to work.  However, the overall suggestions from Ray are ultimately the best suggestions and I completely understand the reasoning.
Ray PaseurCommented:
The only reason why I didn't grade this as excellent is ...
The only reason I didn't write your code for you was that I am a professional and I am not getting paid to write your code.  It's often a good idea to hire a professional.  I never try to cut my own hair.  The outcome is not acceptable, so I pay someone who is an expert and who has the right tools at hand.

Your code does not matter.  Nobody wants to look at code that does not work.  What matters is the data.  Show us the inputs you have and the outputs you need.  If you focus on those elements you will almost always get good answers here at EE and in any other forum.

This is worth learning about: SSCCE

Good luck, ~Ray
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.