Solved

PHP Dynamic Dropdown Selection

Posted on 2013-06-08
16
704 Views
Last Modified: 2013-06-24
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.

code*************************
    <?php      
      // 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)) {
            $selected="";
            $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;

?>
0
Comment
Question by:dalerbrumbaugh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 3
  • +1
16 Comments
 
LVL 9

Expert Comment

by:TvMpt
ID: 39232211
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.

http://www.w3schools.com/php/php_sessions.asp
0
 

Author Comment

by:dalerbrumbaugh
ID: 39232223
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.
0
 
LVL 9

Expert Comment

by:TvMpt
ID: 39232268
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>
    </select>
</form>

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 )
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 7

Expert Comment

by:Robert Saylor
ID: 39232365
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:
<?php

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
0
 

Author Comment

by:dalerbrumbaugh
ID: 39232430
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.
0
 
LVL 7

Expert Comment

by:Robert Saylor
ID: 39232435
I would suggest reading up on sessions. What are you using for your member login? A database to store there details and login data?
0
 

Author Comment

by:dalerbrumbaugh
ID: 39232443
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.
0
 
LVL 9

Expert Comment

by:TvMpt
ID: 39232793
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.
0
 

Author Comment

by:dalerbrumbaugh
ID: 39233137
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?
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39235215
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."
http://php.net/tut.php

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.
http://www.laprbass.com/RAY_temp_dalerbrumbaugh.php

<?php // RAY_temp_dalerbrumbaugh.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28151824.html


// IS THERE A GET-METHOD REQUEST?
if (!empty($_GET['color'][0]))
{
    // YES, SOMETHING WAS SELECTED
    echo '<pre>';
    var_dump($_GET);
    echo '</pre>';
    echo PHP_EOL;
}

// THIS SIMULATES A DATA BASE QUERY
$dat = array
( 'red'
, 'green'
, 'blue'
)
;

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

// BUILD THE HTML DOCUMENT (REQUEST GOES TO ITS OWN URL)
$htm = <<<EOD
<form method="get">
<select name="color[]" multiple>
$opts
</select>
<input type="submit" />
</form>
EOD;

echo $htm;

Open in new window

0
 

Author Comment

by:dalerbrumbaugh
ID: 39236568
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?
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39237452
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.
http://www.amazon.com/PHP-MySQL-Web-Development-Edition/dp/0321833899

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.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Once you've read the code examples in the article, please post back if you still have questions.  Best regards, ~Ray
0
 

Author Comment

by:dalerbrumbaugh
ID: 39255021
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
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39256124
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. :-)
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28151824.html#a39235215

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.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Best regards, and best of luck with your project, ~Ray
0
 

Author Closing Comment

by:dalerbrumbaugh
ID: 39273374
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.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39273540
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
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
This article discusses how to implement server side field validation and display customized error messages to the client.
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question