dalerbrumbaugh
asked on
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['CoCi St']}</opt ion>";
$selected = "selected='selected'";
header("Location: ../Forms/Bookings/Bookings .php?First Name=$stfi rstname&La stName=$st lastnme&us erid=$stid &Address=$ staddress& City=$stci ty&State=$ ststate&Zi p=$stzip&E mail=$stem ail&HomePh one=$stpho ne&MobileP hone=$stce ll");
}
$dropdown .= "\r\n</select>";
// display dropdown.
echo $dropdown;
echo "Testing";
echo $City;
?>
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"
// 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']}'>{
$selected = "selected='selected'";
header("Location: ../Forms/Bookings/Bookings
}
$dropdown .= "\r\n</select>";
// display dropdown.
echo $dropdown;
echo "Testing";
echo $City;
?>
ASKER
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.
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.
You have to refresh the page to get the selected values.
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 )
<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>
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 )
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:
For POST it's the same just replace GET with POST
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";
}
?>
For POST it's the same just replace GET with POST
ASKER
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.
I would suggest reading up on sessions. What are you using for your member login? A database to store there details and login data?
ASKER
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.
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.
ASKER
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?
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
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;
ASKER
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?
As I work with this a question that immediately arises is how to I load my sql query results into the array?
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.
https://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
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.
https://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
ASKER
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
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
http://www.w3schools.com/php/php_sessions.asp