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
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 want to access the value selected by user for further processing.
Hence I am using post method to pass the values of whole form.
But GET to access cust_id so that I can reflect change in
further parts of my form. Hence I had to post the following line:
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
outside php code. But now, once I select some option from dropdown menu, URL changes accordingly, but dropdown menu does not reflects the change
<?php
$query = "SELECT Cust_id, Cust_Name, Cust_City FROM Customers";
$result = mysql_query($query);
?>
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
<?php
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['Cust_id'].'">'.$row['Cust_Name'].','.$row['Cust_City'].'</option>';
}
echo '</select>';
?>
How can I, in the same form, access the address of the particular customer id from database when user selects customer name from this dropdown menu?
I think you mean when you change dropdown, the value is not retained, it obviously won't be because your page is being refresh, you need to GET the value from url and put a selected attribute to have that value selected.
Do it this way:
<?php
$query = "SELECT Cust_id,Cust_Name,Cust_City FROM Customers" ;
$result = mysql_query($query);
//checking if GET variable is set, if yes, get the value
$selected_option = (isset($_GET['product'])) ? $_GET['product'] : '';
//we will store all the dropdown html code in a variable and display it later
$select = "<select id='fullname' onChange=\"window.location='sp_menu.php?product='+this.value\" name='fullname'>";
while($row = mysql_fetch_assoc( $result )) {
//checking if the cust_id matches the GET value,
//if yes, add a selected attribute
$selected = ($selected_option==$row['Cust_id'])?'selected':'';
echo '<option value="'.$row['Cust_id'].'"'. $selected. '>' . $row['Cust_Name'] .' , '.$row['Cust_City']. '</option>';
}
$select .= '</select>';
//display the dropdown
echo $select;
?>
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/
This question already has an answer here:
How to populate second dropdown based on selection of first dropdown using jQuery/AJAX and PHP/MySQL?
(1 answer)
Closed 9 years ago.
I have the following code to generate a dropdown list.
$query = "SELECT * FROM firm";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='name'>";
while($row = mysql_fetch_assoc($result))
$dropdown .= "\r\n<option value='{$row['name']}'>{$row['name']}</option>";
$dropdown .= "\r\n</select>";
How can i modify this code to make a 2nd dropdown based on the value selected in the above drop down.
What i am trying to achieve is that you can firstly select a firm as above, then secondly i want to be able to choose between the different areas for that specific firm. All this information is in one table.
Is it possible to modify this code.
You can bind a change event on the first select element
$("#firm").change(function(){...});
When that happens you need to make an AJAX request to get those extra options for the second select element and then use that result set to populate the new select element.
Here you can see the Javascript implementation of getting that new result set and populating select element: Populate Select box options on click with Javascript/Jquery with Json data
P.S. There is a second option where you don't use AJAX but get all select options first with their relationships to each other and then based on selected item hide/show connected areas in the second select element.
create a function in javascript to generate query string :
<script type="text/javascript">
function show(val){
window.location="pagename.php?drp="+val;
}
</script>
call this function on onchange event of Dropdown:
$dropdown = "<select name='name' onChange='show(this.value)'>";
now a query string generate. fetch query string value in any variable
Bind second Dropdown:
if(isset($_REQUEST["drp"]))
{
$val=$_REQUEST["drp"];
$query = "SELECT * FROM tablename where parametername='$val'";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='drp2'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name']}'>{$row['name']}</option>";
}
$dropdown .= "\r\n</select>";
}
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.