How can I initialize a listbox using a value from a table in the database?
When I'm posting page without doing changes in listbox, application save first value of listbox to the table.
<?php
$cpquery = "Select distinct(operater) from operater where dept='$dept' order by operater";
$cpresult = mysql_query($cpquery) or die(mysql_error());
?>
<select name="operater" value="operater"> <!-- Drop down -->
<?php
if($cpresult) {
while($row = mysql_fetch_array($cpresult)) {
echo '<option value="' .$row['operater']. '">'. $row['operater']. '</option>' ;
}
}
echo "<option value='operater' ></option>";
echo "</select>"; <!-- end of block --> –
Maybe you could use a hidden form input with the "fallback" value, so in PHP you could check if your listbox was changed. If it wasn't, you could use this hidden value.
But I'm not sure I understood your question.
Related
I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.
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/
<select name="parentgroup" type="text" id="select2" onchange="this.form.submit();">
<?php
echo "<option value=\"0\">All Users</option>";
$result = mysql_query("select * from login WHERE stato=1");
while ($myresults = mysql_fetch_array($result))
{
$username = $myresults['user_name'];
echo "<option value=\"".$username."\" ";
echo $username== $parentgroupid ? " selected" : "";
echo ">".$username."</option>";
}
?>
</select>
Hi...am supposed to use the first element in <select> which is <option value=\"0\">All Users</option> to fetch values from a mysql database.
I want to now how you can assign this to a variable and use it just like $parentgroupid
When you submit the form (which presumably exists since you are referencing it from your JavaScript): Get the value from $_GET['name_of_form_control'] in the document referenced by the action attribute of the form.
When you submit the form, depending on the method specified in the form ("GET" or "POST"), the value will be in either the $_GET or $_POST arrays on the page to which you are submitting. You can retrieve the value by name (the name of the control):
$parentgroupid = $_GET['parentgroup'];
or
$parentgroupid = $_POST['parentgroup'];
I generated a drop down menu with the code below. How can I set the field to the GET variable after submit is clicked?
<select>
<?php
$sql="SELECT c FROM problems WHERE b='$id'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["c"];
$c=$row["c"];
$options.="<option value=\"$id\">".$c;
}
?>
<option value=''>C <?=$options?> </option>
</select>
<select>
<?php
$sql="SELECT c FROM problems WHERE b='$id'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["c"];
$c=$row["c"];
if($_GET['var'] == $id)
echo '<option selected="selected" value=\"$id\">' . $c . '</option>';
else
echo '<option value=\"$id\">' . $c . '</option>';
}
?>
</select>
Basic idea is compare value GET data with database data and using if else condition add selected="selected" if condition matched. I am directly printing string as they will not be getting use later on.
I'm a bit confused about what you want to know. To have an option selected by default, use the selected="selected" attribute on that option.
If you want to know how to get the submitted value in PHP, you need to assign the name attribute to the <select> tag. In general, however, you've got the idea right.
I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!