Print selected value from dynamic dropdown php mysql - php

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.

Related

Display session variable as selected in the dropdown of another page

I have set a value in a session variable in 1 page, now I have to display that session variable value on another page's dropdown as selected.
I've tried everything but couldn't get it to work, maybe because of bad coding.
Here is my code:
<select name="subject_id"
class="select-form subjectSelect sub" onchange="ajaxDrp(this.value)"
>
<option value="" style="color:#000">Select</option>
<?php
$sql = "select * from mock_subject ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($subjectId == $obj->id){
echo '<option value="'.obj->id.'"
style="color:#000"
selected >'.$obj- >subject_name.'
</option>';
} else {
echo '<option value="'.$obj->id.'"
style="color:#000">'.($obj->subject_name).'
</option>';
}
}
}
}
?>
</select>
Session is already started, my session variable value is subject'Id, but in the dropdown I have to display subjectId's subject name, and code is like this code session:
$_SESSION["subject"] = "contains subject ID"

How can I get the selected value from a drop down list

I am trying to use a dynamically generated dropdown list to populate a table. I have a drop down list that is generated from my database (it grabs all the years available for a specific player). I want to be able to select a year from the dropdown and have it update my table. I have the dropdown being generated, but I am not able to get the selected value from the dropdown. I have code below that I found here, but it doesn't seem to work. Here is the code I have so far:
<input name="update" type="submit" value="Update" />
</form>
<p></p>
<form action="player_login.html">
<input type="submit" value="Logout" />
</form>
</div>
<div style="float: left">
<p></p>
<h1>Player Stats</h1>
<table width="300" border="1" cellpadding="2" cellspacing="2">
<?php
// get "id" field from player table
$login_id = $_COOKIE["DB"];
$id = "select id from player where login_id='$login_id';";
$result1=mysql_query($id) or die('Select1 Query failed: ' . mysql_error());
$row = mysql_fetch_array($result1);
// create a dropdown from stats table in db
echo "--Select Year--";
$years_query = "select year from stats where player_id='$row[id]';";
$years = mysql_query($years_query, $connect);
// fill array with db info
$var = array();
while ($row2 = mysql_fetch_array($years))
{
$var[] = $row2['year'];
}
// create dropdown
echo'<select name="years" id="years">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select>';
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query) or die('Select2 Query failed: ' . mysql_error());
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
// create table with results
echo "<tr>";
echo "<td>Year</td>";
$j=1;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Total Points</td>";
$j=2;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>PPG</td>";
$j=3;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
?>
</table>
</div>
I see that you use $_POST and since form is not submitted and thus data of $_POST is not set. Best available option I have used to catch the event and send the AJAX Query fetch results and update it.
I have done this with the help of J Query as under
$('#years').change(function() {
$.ajax({
//request of AJAX
type : 'POST',
url : 'players_data.php',
dataType : 'json',
data: {
//Data with $_POST request
years : $('#years').val();
},
success: function(data){
//Things to be done with returned data
}
}};
Create a new file players_data.php and there you write the code for fetching data from the db as:
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query);
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
$return['year']=$line;
echo json_encode($return);
I see that you are using $_POST, and why do you don't use a form?
//This is for get the form
echo '<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>';
//create a form
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
// create dropdown; onchange will send the form when selected index changes...
echo '<select name="years" id="years" onchange="get_form(this).submit(); return false;">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select></form>';
And that's all! :D
I'm seeing too that you are using an unique form for update all the page... It's isn't work, because you only have a submit button and no more element in the form, please read that: http://www.w3schools.com/tags/tag_form.asp
From your code i can see that u want to get the value from the select box and immediately populate the table and display the results..use jquery to get the value of selected object and assign the javascript variable to a php variable. and insert into the db..
<script type="text/javascript">
$( "#years" ).change(function() {
var value=document.getElementById("years").value;
alert(value);
</script>
assign the variable to php and execute you php query.
<?php
$data = "<script>document.write(value)</script>";
//execute your query here..
?>
Also have a look at ajax..it does that so well...

Passing dropdown data which is gatherd from a mysql table

I need a script that loads data form mysql and show on a drop down list. From there, I need to pass the selected data to another page.
I have done the first step. I am now able to load data from mysql table and to show them on a drop down menu. The exact is given bellow.
<?php
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
echo '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
//echo "<option>" . $row['folder_name'] . "</option>";
echo '<option value="'.$row['folder_name'].'">'.$row['folder_name'].'</option>';
}
echo '</select>';// Close your drop down box
?>
Now I need help to pass the selected data to another page. Any suggestion please?
Let me consider the form is posted to page2.php from page1.php
page1.php
<form method="post" action="page2.php">
//your dropdown code here
<?php
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
$str = '';
$str .= '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
$str .= '<option value="'.$row['folder_name'].'">'.$row['folder_name'].'</option>';
}
$str .= '</select>';// Close your drop down box
echo $str;
?>
<input type="submit" value="submit" />
</form>
in page2.php you can access the dropdown selected value as
$selVal = '';
if(isset($_POST['directory']))
{
$selVal = $_POST['directory'];
}
create a javascript function to handle the redirect with the folder name data:
function changePage(folder){
window.location.href= 'http://www.yourdomain.com/page2.php?folder=' + folder;
}
onchange option, trigger changePage javascript function with folder name as input:
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
echo '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['folder_name'].'" onchange="changePage(\''.$row['folder_name'].'\')">'.$row['folder_name'].'</option>';
}
echo '</select>';// Close your drop down box
page2.php
$folder_name = strip_tags($_GET['folder']);

How to save drop-down list choice upon update using PHP/HTML?

I want to create a drop down list that allows the user to choose a value that is pulled from a database. When the page is updated based on the chosen value, the choice is reverted to the "original," default choice. How can I allow the selected value to save and remain when the page is updated?
// Drop Down Menu to choose Session
if (isset($_POST['action']))
{
$action = $_POST['action'];
$session = $_POST['session'];
}
else
{
$action = "";
if (!isset($_POST['session']))
{
$session = "";
}
else
{
$session = $_POST['session'];
}
}
?>
<form name='update' action='emailinquiry_webinarnew.php' method='POST'>
Session:
<select name='session'>
<?php
$query = "SELECT distinct session FROM web_attendees";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<option>".$row['session']."</option>";
}
?>
</select>
<input type='submit' name="ViewButton" value='View'/>
</form>
while ($row = mysql_fetch_assoc($result)) {
if($row['session']==$session){
echo "<option selected='selected' >".$row['session']."</option>";
} else {
echo "<option >".$row['session']."</option>";
}
}
hope it will work for you fine...
Just add such condition in the while loop that prints the options to add the selected="selected" that will select the option by default:
while ($row = mysql_fetch_assoc($result))
{
$selected = '';
if (isset($_POST['session']) && $row['session'] == $_POST['session'])
$selected = ' selected="selected"';
echo "<option{$selected}>".$row['session']."</option>";
}

Retaining value of query generated dropdown box after submission

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>';

Categories