Retaining value of query generated dropdown box after submission - php

I populated the options for a dropdown box using the results of a query. How do I retain the selected value after the user submits?
Here's the code:
$query="SELECT trainingName,trainingID FROM training ORDER BY trainingName";
$result = mysql_query ($query);
echo "<select name='training' value=selected>Training Name</option>";
$training = strip_tags(#$_POST['training']);
echo "<option>---------------------Select---------------------</option>";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[trainingID]>$nt[trainingName]</option>";
}
Thanks!

Try this:
$query="SELECT trainingName,trainingID FROM training ORDER BY trainingName";
$result = mysql_query ($query);
echo "<select name='training'>";
echo "<option>---------------------Select---------------------</option>";
while($nt=mysql_fetch_array($result)){
$selected = false;
// check if the current value equals the value submited
if($_POST['training'] == $nt['trainingID']){
$selected = true;
}
// show selected attribute only if $selected is true
echo "<option value='{$nt['trainingID']}' ". ($selected ? "selected" : "") .">{$nt['trainingName']}</option>";
}
echo '</select>';

Related

Print selected value from dynamic dropdown php mysql

I have the below code where I can get dynamic value into drop down list from mysql db but i can't print selected value when i click on submit button.
can anyone help me urgntly ?
<?php
include("includes/config.inc.php");
$query = "SELECT * FROM category";
$result = mysql_query ($query);
echo "<select class='turnintodropdown' name='CategoryID' ><option value=''>All</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['CategoryID'].">".$r['CategoryName']."</option>";
}
echo "</select>";
if (isset($_POST['submit'])) {
$selected_val = $_POST['CategoryID']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
?>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
If you want to preselect the selected value of the then you can use the following code. Also check your form method attrivute to see if it set to post (note that mysql_* functions are deprecated, it's better to use PDO using prepared statements).
while($r = mysql_fetch_array($result)) {
if (!empty($_POST['CategoryID']) && $_POST['CategoryID'] == $r['CategoryID']) {
$selected = 'selected="selected"';
} else {
$selected = '';
}
echo "<option ".$selected." value=".$r['CategoryID'].">".$r['CategoryName']."</option>";
}
from above:
echo "you have selected :" . $selected_val;
from what you are echoing, based on what I'm exp[laining], it echos the ID, not the name of the category.

Clear select option after successful submit

<div class="select_list">
<div class="labels">Category:</div>
<?php
if(!isset($_POST['postbtn)){
echo "<script>$(document).ready(function(){
$('.category').val(0);
})
</script>";
}
echo "<select name='category' id='catg_list' class='list_catg'>
<option value='0'";
if(isset($_POST['category']) && $_POST['category']=='0'){
echo "selected";
}
echo">none</option>";
$query = mysql_query("SELECT id, name from table1");
while($query_fetch = mysql_fetch_assoc($query)){
echo "<option value='".$query_fetch['id']."'";
if(isset($_POST['category']) && $_POST['category']==$query_fetch['id'])
{
echo "selected";
}
echo ">".$query_fetch['name']."</option>";
}
echo "</select>";
?>
</div>
The problem with the above code is that the selected element stays selected after the submission is done. I need the select option to return back to 'none' when the form is submitted successfully. How can that be done?
You have an syntax error in your line:
if(!isset($_POST['postbtn)){
change it to:
if(!isset($_POST['postbtn'])){
I'm guessing some things you didn't mention:
You validate your script above the code you posted, and you want - if the script was validated successfully - that the "none" option is selected.
$selected_value = $validation ? $_POST['category'] : false;
Only if the Validation is correct the value will be set, else it will be set to false;
<?php
echo "<select name='category' id='catg_list' class='list_catg'>
<option value='0'";
//CHANGE
if($selected_value == 0){ //Or if($selected_value === FALSE ||$selected_value === 0)
echo "selected";
}
echo">none</option>";
$query = mysql_query("SELECT id, name from table1");
while($query_fetch = mysql_fetch_assoc($query)){
echo "<option value='".$query_fetch['id']."'";
//CHANGE
if($selected_value !== FALSE && $selected_value == $query_fetch['id'])
{
echo "selected";
}
echo ">".$query_fetch['name']."</option>";
}
echo "</select>";
?>
Simplify your code as following to do required task.
$category = isset($_POST['category']) ? $_POST['category'] : 0;
$array["0"]="none";
$query = mysql_query("SELECT id, name from table1");
while($query_fetch = mysql_fetch_assoc($query)){
$id = $query_fetch['id'];
$array[$id] = $query_fetch['name'];
}
echo "<select name='category' id='catg_list' class='list_catg'>";
foreach($array as $id=>$name) {
$selected = $category==$id ? "selected" : "";
echo "<option value='".$id."' ".$selected." >".$name."</option>";
}
echo "</select>";

Attribute selected inside while

I have a script that get all ids from a table and print them on option select form, and i want to reload page with the id i chose as selected on option. This is the script:
<?php
include('include/menu.php');
include('include/mysql.php');
if ($db_found) {
echo "<form action='' name='form' method ='get'>
<select name='funcionario'>";
$SQL = "SELECT * FROM funcionarios";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
$idfunc = $_GET['funcionario'];
$selected = ($idfunc==$idfunc->$db_field['idfunc']) ? ' selected="selected"' : '';
echo "<option value'".$db_field['idfunc']."' ".$select." onclick='document.form.submit();' >".$db_field['nomefunc']."</option>";
}
echo "</selected></form>";
echo $idfunc;
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
But the script are always returning only the first id as selected.
Remove $idfunc-> from $idfunc->$db_field['idfunc']
Replace value'".$db_field['idfunc']."' with value='".$db_field['idfunc']."'
You already defined $idfunc = $_GET['functionario'] which is a string, not an class object.
Also you defined $selected but you are using $select when echoing the result.
For further debugging, use error_reporting(E_ALL); at the top of your script. I guess that's why you didn't get error when you tried to execute this script.
Here's complete script:
<?php
include('include/menu.php');
include('include/mysql.php');
if ($db_found) {
echo "<form action='' name='form' method ='get'>
<select name='funcionario'>";
$SQL = "SELECT * FROM funcionarios";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
$idfunc = $_GET['funcionario'];
$selected = ($idfunc==$db_field['idfunc']) ? ' selected="selected"' : '';
echo "<option value='".$db_field['idfunc']."' $selected onclick='document.form.submit();'>".$db_field['nomefunc']."</option>";
}
echo "</selected></form>";
echo $idfunc;
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
$selected = ($idfunc)==$db_field['idfunc'] ? ' selected="selected"' : '';
echo "<option value'".$db_field['idfunc']."' ".$selected." onclick='document.form.submit();' >".$db_field['nomefunc']."</option>";
I hope this is you want! Try this!

Display drowdown values after user has selected 3 option

I have 3 drop downs I want to display whatever the user will select after he/she has selected a function or a scrpt will do but it must be within the script
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="test.php">';
//Names dropdown:
echo '<select name="id" id="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="id" id="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="id" id="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo "<button id='write_in_div'>Click me!</button>";
echo '</form>';
}
?>
Something that will call the write_in_div When Click me! button is press or any other method that can be used to display 3 selection user selected
The Output should be something like You select 1) Name 2)Surname and Email
You have an error in your html selects each select has the same name "id" they each need to be unique so you can detect then.
You need to detect if the user has submitted the form
if(isset($_POST["select_name"])) {
echo $_POST["select_name"];
}
There is a big mistake on you form.
In a form, each select and input MUST have a unique name. You need this name to retrieve the submitted value back in your php script.
I suppose you have this:
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form method="post" action="test.php">';
//Names dropdown:
echo '<select name="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo '<button id="write_in_div">Click me!</button>';
echo '</form>';
}
When the form is submitted, test.php will have the posted data: $_REQUEST['names'], $_REQUEST['surnames'] and $_REQUEST['emails'].
You just have to check the content of thoses vars and print them if not null.
Note1: ?> is useless at the end of a file.
Note2: be carefull about ' and " when writing an html file. The value of an html attribute is written with ", not '.

Edit drop down but not showing selected value from mysql data base in php

I am new to php, i created drop down which calling data from mysql data base, user selects option and its save to data base.
Problem Arises in edit form in which its do not showing selected value.
Drop Down code is below:
$query = 'SELECT name FROM owner';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//create selection list
echo "<select name='owner'>\name";
while($row = mysql_fetch_row($result))
{
$heading = $row[0];
echo "<option value='$heading'>$heading\n";
}
echo "</select>"
Please advise solution for the edit form.
Thanks in Advance
you must close <option> tag:
echo "<option value='$heading'>$heading</option>";
$query = 'SELECT name FROM owner';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//create selection list
echo "<select name='owner'>\name";
while($row = mysql_fetch_row($result))
{
$heading = $row[0];
?>
<option <?php if($heading=="SOMETHING") { echo "selected='selected'"; } ?> value="SOMETHING">SOMETHING</option>
<option <?php if($heading=="SOMETHING2") { echo "selected='selected'"; } ?> value="SOMETHING2">SOMETHING2</option>
<option <?php if($heading=="SOMETHING3") { echo "selected='selected'"; } ?> value="SOMETHING3">SOMETHING3</option>
<?php
}
echo "</select>"
I'd do it this way.
$numrows = mysql_num_rows($result);
if ($numrows != 0){
echo "<select name='owner'>\name";
while ($x = mysql_fetch_assoc($result)){
echo "<option value='".$x['heading']."'>".$x['heading']."</option>";
}
echo "</select>";
}
$x['heading'] is using the value of the row 'heading' in the database
It's much more efficient and simply looks more sophisticated.

Categories