Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 744
  • Last Modified:

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.

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
dalerbrumbaugh
Asked:
dalerbrumbaugh
  • 7
  • 4
  • 3
  • +1
1 Solution
 
TvMptCommented:
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
 
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.
0
 
TvMptCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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:
<?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
 
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.
0
 
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?
0
 
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.
0
 
TvMptCommented:
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
 
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?
0
 
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."
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
 
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?
0
 
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.
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
 
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
0
 
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. :-)
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
 
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.
0
 
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
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 7
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now