This question already has answers here:
Showing the selected value in Drop down select using PHP
(4 answers)
Closed 8 years ago.
I have a form and here is the code for the dropdown menu. Can you help me with the code to show the selected value after submitting the form? im using php
<?php
$result = mysql_query("SELECT * FROM professional") or die(mysql_error());
if (mysql_num_rows($result)!=0)
{
echo '<select name="professional">
<option value=" " selected="selected">Choose one</option>';
while($row = mysql_fetch_array( $result ))
{
echo '<option value="'.$row['prcno'].'">'.$row['prcno']."\t"."|\t".$row['name']."\t"."|\t".$row['profession'].'</option>';
}
echo '</select>';
}
?>
You will have two Superglobal variables available to you: $_GET and $_POST.
These are arrays, and the key for each is the name of any submitted form element, whether it was POSTED or sent with GET parameters.
See: http://www.php.net/manual/en/reserved.variables.post.php and http://www.php.net/manual/en/reserved.variables.get.php
To display a value would be as simple as:
<?php echo $_POST['form-element-name']; ?>
Suppose you are receiving the selected value in $_POST['professional'] then in your code, you should write as -
<?php
$result = mysql_query("SELECT * FROM professional") or die(mysql_error());
if (mysql_num_rows($result)!=0)
{
echo '<select name="professional"> ';
if(isset($_POST['professional']))
if($_POST['professional']=="")
echo '<option value="" selected>Choose one</option>';
while($row = mysql_fetch_array( $result ))
{
if(isset($_POST['professional']))
if($_POST['professional'] == $row['prcno'])
echo '<option value="'.$row['prcno'].'" selected>'.$row['prcno']."\t"."|\t".$row['name']."\t"."|\t".$row['profession'].'</option>';
else
echo '<option value="'.$row['prcno'].'">'.$row['prcno']."\t"."|\t".$row['name']."\t"."|\t".$row['profession'].'</option>';
}
echo '</select>';
}
?>
Related
How would one populate a child drop down selection on a static page from a parent drop down using only PHP. E.g having a child drop down populate with counties after you have selected which state you live in, or in my case populate series after manufacturer.
EDIT: Is there a way to do it without js?
<?php
$man = mysqli_query($con,"SELECT DISTINCT manufacturer FROM inventory.manufacturer WHERE manufacturer!=\"\" ORDER BY manufacturer;");
echo "<select name=\"manufacturerS\">
<option value=\"\">Select</option>";
while($row = mysqli_fetch_array($man)) {
echo "<option value=\"".$row['manufacturer']."\">".$row['manufacturer']."</option>";
}
echo "</td>
<td>";
if(isset($_POST['manufacturerS'])){
$ser = mysqli_query($con,"SELECT DISTINCT series, manufacturer FROM inventory.audit WHERE series!=\"\" AND manufacturer='".$_POST['manufacturerS']."' ORDER BY series;");
echo "<select name=\"seriesS\">
<option value=\"\">Select</option>";
while($row = mysqli_fetch_array($ser)) {
echo "<option value=\"".$row['series']."\">".$row['series']."</option>";
}
echo "</td>
<td>";
}
You need of client-side to determine when manufacturerS select was selected, then you can use pure javascript:
<form id="manufacturerF" method="POST">
<select name="manufacturerS" onchange="document.getElementById('manufacturerF').submit();">
<?php
$man = mysqli_query($con, "SELECT DISTINCT manufacturer
FROM inventory.manufacturer
WHERE manufacturer!=\"\"
ORDER BY manufacturer;");
while ($row = mysqli_fetch_array($man)) {
echo '<option value="'.$row['manufacturer'].'>'.$row['manufacturer'].'</option>';
}
?>
</select>
</form>
<?php
if(isset($_POST['manufacturerS']) && !empty($_POST['manufacturerS'])){
echo '<select name="seriesS">';
$ser = mysqli_query($con,"SELECT DISTINCT series, manufacturer
FROM inventory.audit
WHERE series!=\"\"
AND manufacturer='".$_POST['manufacturerS']."'
ORDER BY series;");
while ($row = mysqli_fetch_array($ser)) {
echo '<option value="'.$row['series'].'">'.$row['series'].'</option>';
}
echo '</select>';
}
?>
I recommend you use JQuery so will not need a <form> and reload your page.
The correct idea would be to use JQUERY to detect when the select1 was selected and then with AJAX populate the select2
I would like to remain my drop down value which I select for submitting after posting the form. My form posts to the same page.
$query = "SELECT countryName,countryCode FROM tcf_countries";
$result = mysql_query ($query);
echo "Country: <select name='country' value=''>";
while($r = mysql_fetch_array($result)) {
$id = $r['countryCode'];
$cname = $r['countryName'];
echo "<option value=".$id.">".$cname."</option>";
}
echo "</select>"; ?>
Remove your current echo inside the loop and replace it with the following:
if($_POST["country"]==$id)
echo "<option value='".$id."' selected='selected'>".$cname."</option>";
else
echo "<option value='".$id."' >".$cname."</option>";
This will check if the current option being displayed is the one that was submitted and it will select it in that case.
If I understand what you are looking for correctly you need to use the $_POST value of your select to set the selected item...
$query = "SELECT countryName,countryCode FROM tcf_countries";
$result = mysql_query ($query);
$country = '';
echo "Country: <select name='country'>";
while($r = mysqli_fetch_array($result)) {
$id = $r['countryCode'];
$cname = $r['countryName'];
echo "<option value=".$id;
echo ($_POST["country"]==$id) ? ' selected="SELECTED"' : '';
echo ">".$cname."</option>";
}
echo "</select>"; ?>
Setting selected="SELECTED" for the $id that matches $_POST['country'] will make it the selected item in your dropdown.
And, get rid of mysql* functions and use mysqli* functions instead...
I am trying to keep the answer that the user selected and display it once the form has been submitted and there are errors somewhere. This is so the form is not tedious and the user does not have to keep inserting the same values into the form once it has been submitted.
I have been successful in completing this for options that are not dynamically generated from database values:
<option
<?php if($_POST['condition'] == 'acceptable') {
echo 'selected="selected"';
}?> value="acceptable">Acceptable
</option>
That works fine! Now the problem is how do I do this for this form option?
<option value="select">- Select school -</option>
<?php
$result = mysqli_query($con,"SELECT `name` FROM school");
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['name'].'">'.$row['name'].' School</option>';}?>
</select>
I have tried this so far but I cannot get it to work:
$result = mysqli_query($con,"SELECT `name` FROM school");
while($row = mysqli_fetch_array($result)) {
if($_POST['school'] == '$row["name"]') {
$selected = 'selected="selected"';
}
echo '<option $selected value="'.$row['name'].'">'.$row['name'].' School</option>';}
You don't need to store that "selected" attribute in a variable,
just print it.
Dividing the echo to 2 allows you to insert a condition between them.
Another note: you did you wrapped the variable with '? You don't need to.
echo '<option value="'.$row['name'].'"';
if($_POST['school'] == $row["name"]) {
echo ' selected="selected"';
echo '>'.$row['name'].' School</option>';}?>
Change. In single qoutes echo doesnt interprets $selected as variable :
$result = mysqli_query($con,"SELECT `name` FROM school");
while($row = mysqli_fetch_array($result)) {
if($_POST['school'] == '$row["name"]') {
$selected = 'selected="selected"';
}
echo '<option '.$selected.' value="'.$row['name'].'">'.$row['name'].' School</option>';
}
So I have this drop down list in my form which pull "tags" from database as value for drop down options:
<select name="cartags">
<?php $result = mysql_query("SELECT * FROM Products WHERE ID > '0'");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['Tag']; echo "\""; echo ">"; echo $row['Tag']; echo "</option>";
}
?>
</select>
What is my problem? My problem is that I am adding a lot of products into my databas and my code make dropdown list with tags for all this producst even if they have same tag. So what I need is solution how to prevent that same tag appear twice in my drop down.
I am pretty new to PHP and this is my first question here so I really hope that I explained my problem well.
Thanks in advance!
What is the purpose of WHERE ID > '0'? If ID is an auto-increment then it will always be positive. If not, it should be.
Why are you using mysql_fetch_array and then only using the associative keys? You should use mysql_fetch_assoc instead.
Why are you using a new echo every time you want to output a variable? Just concatenate.
Why are you setting the same string in value as the option's text? Without a value, it defaults to the text anyway.
Why are you not using backticks around your column and table names?
Try this instead:
<select name="cartags">
<?php
$result = mysql_query("SELECT DISTINCT `Tag` FROM `Products`");
while(list($tag) = mysql_fetch_row($result)) {
echo "<option>".$tag."</option>";
}
?>
</select>
Try this
<select name="cartags">
<?php $result = mysql_query("SELECT Tag, COUNT(Tag) tg Products WHERE ID > '0' GROUP BY Tag HAVING COUNT(Tag)>0 ORDER BY tg DESC");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['tg']; echo "\""; echo ">"; echo $row['tg']; echo " </option>";
}
?>
</select>
It will also display the top tags that have the most first.
This question already has answers here:
Fetching data from MySQL database to HTML dropdown list
(4 answers)
Closed 7 months ago.
<select name="select">
</select>
I want to populate the above tag with values from database.
I have written PHP code up to this.
while($row=mysql_fetch_array($result))
{
}
$row is fetching correct values. How to add it to the <select>
What about something like this :
echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['column_for_value']) . '">'
. htmlspecialchars($row['column_for_label'])
. '</option>';
}
echo '</select>';
Of course, up to you to decide which items from $row should be used for the value and the text of each <option>
Just make sure you are escaping the data that comes from your DB -- especially if it can contain HTML ; as you are outputting HTML, this can be done with htmlspecialchars or htmlentities.
Note that those might take a couple of additionnal parameters that I didn't use in my example -- setting those can be useful, depending on the charset you're using.
You can see whats available to use by doing this in the while:
var_dump($result);
exit;
That will print the first result and its array contents. Then you can see what field you want to use to populate the option. From there, you would do something like:
foreach ($result['field'] as $field) {
print '<option value="'.$field.'">$field</option>';
}
Of course this is a very basic example, and as others have noted you may want to clean the data before putting it into a form.
$selected_value="selected_value";
echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
if($selected_value==htmlspecialchars($row['column_for_value']))
$selected=' selected';
else
$selected='';
echo '<option value="'.htmlspecialchars($row['column_for_value']).'"'.$selected.'>'
.htmlspecialchars($row['column_for_label']).
'</option>';
}
echo '</select>';
Some addition to Pascal MARTIN code, for auto selection of some predefined value
I editied the last entry to this and it works perfectly. The only hassle I have now is once the user has submitted the form the dropdown goes blank... Does anyone know a simple solution
echo '<select name="course" id="course" >';
while( $option = mysql_fetch_array($course_results)) {
echo "<option value=".htmlspecialchars($option['cid']).">".htmlspecialchars($option['cname'])."</option>";
}
echo "</select>";
All the above answers will work, but are not proper and require extra work. You should not use echo to output to the screen and you don't have to. The below example assumes you are using objects containing data, but you get the idea.
<select name="sales_person">
<?php foreach ($sales_people as $sales_person){?>
<option value="<?=$sales_person->first_name?> <?=$sales_person->last_name?>"><?=$sales_person->first_name?> <?=$sales_person->last_name?></option>
<?php }?>
</select>
The point being you don't have to echo out the html
echo "<select>";
while( $option = mysql_fetch_array($result)) {
echo "<option>".htmlspecialchars($option['column'])."</option>";
}
echo "</select>";
echo '<select>';
while($row=mysql_fetch_array($result)) {
echo '<option>'.$row['whatever_index'].'</option>';
}
echo '</select>';
Replace 'whatever_index' with the column name you are fetching.