I have a dropdown box that I construct with PHP. Here is the code:
$region_result = mysql_query("SELECT * FROM region ORDER BY region");
$dropdown = "<select name='region'>";
while($row = mysql_fetch_assoc($region_result)) {
$rid = $row["id"];
$region = $row["region"];
$dropdown .= "\r\n<option value='{$row['rid']}'>{$region}</option>";
}
$dropdown .= "\r\n</select>";
I need to set the selected value of the dropdown box AFTER the above code is processed. Is there any easy way to do this?
Does anyone have any suggestions? Thanks!
EDIT:
Thank you all for your answers. Let me explain what I am doing. I was setting up an "Edit Users" page, where you can search for a user by multiple criteria and then the results are listed in an "edit mode" - that is - in text boxes and dropdown boxes. So you can then edit and update a user. For two user fields, I need to list the data in dropdown boxes (to ensure data integrity and constraints). So, I want to show those dropdown boxes with all the possible values you can change to, except I want the selected value of the dropdown to be the one currently associated with the user.
So, I was able to get this working with deceze's suggestion - In my while loop that has that is setting my PHP values with the database results, I have inserted a nested while loop which will construct $dropdown, and within that, a nested if-loop. I'm not crazy about all these nested loops. Here is the code segment for that:
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$fname = $r["fname"];
$lname = $r["lname"];
$region = $r["region"];
$role = $r["role"];
$extension = $r["extension"];
$username = $r["username"];
$building = $r["building"];
$room = $r["room"];?>
<?php
$dropdown = "<select name='region'>";
while($row = mysql_fetch_assoc($region_result)) {
$rid = $row["id"];
$region2 = $row["region"];
if($region == $region2){
$dropdown .= "\r\n<option selected='selected' value='{$row['rid']}'>{$region}</option>";
}else{
$dropdown .= "\r\n<option value='{$row['rid']}'>{$region2}</option>";
}
}
$dropdown .= "\r\n</select>";
?>
However, I am considering changing this to the text replacement (suggested by soulscratch and zombat), as I think it would be better on performance.
...This doesn't seem to work when more than one result set meets the search criteria, though (as the dropdown boxes for the 2nd and 3rd and etc. results are empty).
What do you guys think?
With the way your string is built, it's a fairly simple str_replace(), which is nice as it saves the hassle of needing regular expressions:
$dropdown = str_replace("value='".$rid."'","value='".$rid."' selected=\"selected\"",$dropdown);
If you want to change your assembled HTML after the fact you need to use complicated string replace methods, or Javascript, neither of which is a good choice.
The best option you have would be to restructure your program so you can set the selected attribute when going through the loop the first time around.
You will be able to find it in $_REQUEST['region']
I'll bet you'll run into this problem again, which means it'd be worthwhile to come up with a more flexible solution. Here's an idea toward that end:
First, use an array to hold options for your drop-down list. If you need multiple select elements with the same options, you get to re-use the array for free:
$options = array ();
while ($row = mysql_fetch_assoc($region_result)) {
$options[$row['id']] = $row['region'];
}
Then, you can feed this into a function that generates a select control:
function getSelect ($name, $options, $current)
{
$markup = '<select name="' . htmlspecialchars($name) . '">';
foreach ($options as $value => $label)
{
$selected = ($value == $current) ? ' selected="selected"' : '';
$markup .= sprintf(
"<option value=\"%s\"%s>%s</option>\r\n",
htmlspecialchars($value),
$selected,
htmlspecialchars($label)
);
}
$markup .= '</select>';
return $markup;
}
(You can also add one or more optional parameters to set the id, class, etc.)
Also, you mentioned you were considering switching methods because of speed, but it's very unlikely that this is the time and place to worry about performance. Focus on maintainable code now, and any performance tweaks that become necessary later will be easier and more effective.
Related
I have a select box being filled in with a mysql query, it functions fine and is selectable. Data changes and works fine.
It currently sorts based on the branch_id column and what I want is the session variable of $branch_id to be the first option of the select box. This is based on the branch selected from a previous page.
This is where I am stuck.
Here is some sample code of the branch dropdown.
This selection then changes a list of users that appears in an options box below this code. It all functions fine, I just need to refine it so the currently selected branch(from a prev page) is the first in the branch dropdown.
If anyone can help I'd really appreciate it.
//get list of allowed Branchs
$AllowBranch = "SELECT branch_id FROM access WHERE userid IN (SELECT id FROM user WHERE username = '{$_SESSION['user']}') ORDER BY branch_id ASC";
$getAllowBranch = mysql_query($AllowBranch);
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<OPTION VALUE = '{$getAllowBranchRow['branch_id']}' "; if($NeedBranch == $getAllowBranchRow['branch_id']) { echo "selected"; } echo "> ".ucwords(strtolower($Namerow['name']));
}
echo "</SELECT>";
Check the source code to see if the selected attribute is put in the right option tag. Also, you forgot to close every <option> tag with a </option>, not sure, but this could also be the problem.
First of all, you have missing tag <select name="<your field name>"> before while loop.
Then you have missing closing tag </option> too. You cannot solve your problem, if you have HTML broken.
So, it should looks like this:
echo '<select name="<your field name>">';
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<option value='" . $getAllowBranchRow['branch_id'] . "'" . $NeedBranch == $getAllowBranchRow['branch_id'] ? " selected" : "" . ">" . ucwords(strtolower($Namerow['name'])) . "</option>";
}
echo "</select>";
What I have done?
Firstly, I fixed your missing HTML tags. Then I just simply used ternary operator to check if branch_id equals to $NeedBrach and if yes, add following string selected and if not, add nothing.
Don't forget to replace <your field name> with your expect select name.
Important final thoughts!
I have to remind using mysql_* is deprecated, you should use mysqli_* or PDO instead with prepared statements.
I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/
I am new to php and web programming.
I am programming a website that collects essays. In the submission form, I want the date to be entered by 3 select dropdown forms (day-month-year). I used to add them in a text field and save them as strings in database. I added already hundreds of essays so I am not changing the type of data.
I did the following:
1- I made a dynamic dropdown using php:
function get_dropdown_options( $name, array $options, $selected=null ) {
$dropdown = '<select name="'.$name.'" id="'.$name.'">'."\n";
$selected = $selected;
foreach( $options as $key=>$option )
{
$select = $selected==$key ? ' selected' : null;
$dropdown .= '<option value="'.$key.'"'.$select.'>'.$option.'</option>'."\n";
}
$dropdown .= '</select>'."\n";
return $dropdown; }
2- then I made a function to show three dropdown menus for days, months and years.
function show_date_dropdown_row($name, $label, $option1, $option2, $option3, $value = "") {
echo "<tr class=\"".get_row_bg()."\" valign='top'>\n<td><p class=\"rowtitle\">".$label."</p></td>\n";
echo "<td><p>\n";
echo get_dropdown_options($name1, $option1, $value1).get_dropdown_options($name2, $option2, $value2).get_dropdown_options($name3, $option3, $value3);
return $name = $name1." - ".$name2." - ".$name3;
}
3- in the submission form page, I put the following code:
show_date_dropdown_row("release_date", "Release Date", $days_list, $months_list, $years_list, "");
4- the name "release_date" is then added to the database.
The page shows the three dropdown lists perfectly. But the problem is that the "release_date" in database don't store any value.
I tried the function in step1 and it works perfectly. I know that the problem is in step two, but don't know where.
First your return statement inside show_dropdown_row will not provide you with the date you want. That function will run only once when user request for the page.
So instead of $name1,$name2 and $name3 in your get_dropdown_options function you should put values like. day,month and year as names for your select elements.
When submiting your form at on your php script you should catch those value using post or get.
like.
$dates=$_POST['year']."-".$_POST['month']."-".$_POST['day'];
I have this code to collect categories from the field "category" from Mysql, it is a part editing form, i want the category that was selected before to be selected after the list is filled, the code is :
<td align="right">Category</td>
<td>
<?php
// Write out our query.
$query = "SELECT id,cat_name,parent FROM categories WHERE parent='0'";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='category'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['id']}'>{$row['cat_name']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
</td>
I don't know how to do it? i know that i should type "selected" on the option i want to select but how to choose it after i filled the list?
You could use an indexed tab $tab["key"] this way you can easily find the line that you want and edit it.
Edit: Your message isn't very clear, but I figured that's want you want to do. Otherwise, clarify please.
In your code you're not checking what the user has selected previously. You can do that with something like this:
$selected = '';
if($row['id']==$userSelectedOption) $selected = ' selected="selected"';
$dropdown .= "\r\n<option value='{$row['id']}'{$selected}>{$row['cat_name']}</option>";
In the above example, we have a variable named $userSelectedOption which represents the value a user has already selected. We're also assuming that it is the ID of a category. Within your while loop you would use the above 3 line instead of your one line. When this renders out the list will have the selected item be whatever matches $userSelectedOption
As I only have one value in the first dropdown, I am trying to create a cascading dropdown in PHP that populates the second dropdown on page load.
My database has a table called 'nights' with fields called: 'city', 'name' and 'day'.
To fill my first box I'm using SELECT DISTINCT cities from nights etc which has worked fine.
To fill the second box I need something along the lines of SELECT name WHERE city = $city - my problem is that I'm not sure how to set $city (being the name of the <select> tag). I can't use $_POST['city'] because the form hasn't been sent at this point.
Any ideas?
If you want this to be dynamic (i.e. after the user changes the dropdown) you will have to use javascript to firstly query a PHP page (probably using jQuery get) then adjust the dropdowns accordingly. There are lots of tutorials for this on the web.
If you just want the initial page data to be populated you can pick the first city from your query and set the option as selected, then use that city in your next query.
Something like:
$first = True;
while($row = mysql_fetch_array($result))
{
echo "<option" . (($first) ? " selected" : "") . ">" . $row['city'] . "</option>";
if($first)
{
$first = !$first;
$city = $row['city'];
}
}
//now do stuff with with $city
<?
$CITIES = query_result("SELECT DISTINCT cities FROM nights;");
if (isset($_POST["city"])) {
$NAMES = query_result("SELECT name FROM nights WHERE city = '{$_POST[city]}'");
if (isset($_POST["day"])
$DAYS = query_result("SELECT day FROM nights WHERE city='{$_POST[city]}'".
" AND name = '{$_POST[name]}'");
else
$DAYS = array();
} else
$NAMES = array();
/* now output the <select> markup for $CITIES, $NAMES and $DAYS */
?>
Note: you have to define the query_result function yourself (I just used it to simplify the code).
You can use AJAX for this.
On change event call javascript-ajax function that call php script which makes you second dropdown caode.
You will need to use ajax to load options from php script.
Here is an example of how you can do it with jquery and ajax:
Autopopulate Select Dropdown Box Using jQuery