Maintain select values from dynamic drop down list after refresh - php

I have a form consisting of 11 elements (input and select tags). The form has form validation that prompts an error message next to field when a user inputs incorrect data. I want to maintain the correct data entered into the fields after the page is refreshed.
For instance, let's say that 10 fields where populated correctly and 1 field incorrectly. When the user presses the submit button, an error message is shown near the field. What I want to do is to keep the 10 correct values selected so the user does no have to start all over again.
For the input elements, this is working fine but for the select elements this is not working. Important is that I am populating the drop down list dynamically with PHP.
Is this possible to do in PHP since I cannot figure out how?
Below is an example of how I am generating a drop down list of a select element.
select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
echo '<option value="' . htmlspecialchars($row['description']) . '">'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As for the input elements I am achieving this using the below:
<input type="text" name="serial" value="<?php echo $serial;?>">

Try this:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>

As outlined in the as duplicate linked question the selected attribute is to mark the option that has been submitted. The selected attribute addresses the issue to make the selected value visible.
Additionally your code can benefit from data-binding the select element to the (SQL) data in a modular way.
Let us not care for a moment on the retrieval of the data and just say they come from a Generator:
/**
* #param string $name of the select field
* #param string $value of the select field
* #param Generator $data to use as select field option values
* #return string HTML of the select element
*/
function select($name, $value, Generator $data) {
$buffer = sprintf('<select name="%s">', htmlspecialchars($name));
foreach ($data as $option) {
$buffer .= sprintf(
'<option%s>%s</option>',
$value === $option ? ' selected' : '',
htmlspecialchars($option)
);
}
$buffer .= "</select>\n";
return $buffer;
}
This little function returns the HMTL of a select element with the data from a Generator selecting an existing value (if part of the options).
Combining it with any generator, for example from a data-source, it can be easily put into your forms template script:
<form method="post">
<?= select('location', $_POST['location'] ?? 'default value',
datasource($connection, "SELECT description FROM location ORDER BY description ASC", "description")
) ?>
</form>
So if you've got 10 selects, this can be easily adopted. As the database connection as you know it is passed to the datasource function, it would be interesting to see what that function actually does. That function is even more simple:
/**
* #param mysqli $mysqli
* #param string $query
* #param string $field from query result to use as option values
* #return Generator
*/
function datasource(mysqli $mysqli, $query, $field) {
$result = $mysqli->query($query);
if ($result) foreach ($result as $row) {
yield $row[$field];
}
}
It queries the query on the database connection (it's a different way of writing as in your code, but it's the same $connection as in your example) and then iterates over the result (if there is a result). Then yielding each option value. That yield is a special form of returning from a function creating a Generator which is used in the select function for output, by having the Generator in the foreach loop there. Each yielding becomes one iteration of the Generator.
I hope this shows how you can benefit from dividing your code into functions. Values that change should be put into variables. This is easily done by creating functions and using parameters for these values. You sort of extend the language to your own special needs, like creating select elements.

Is this possible to do in PHP since I cannot figure out how?
Yes it is possible to keep the values selected, by using the selected attribute on the option elements.
For instance, the <option> tag below contains that attribute:
<option value="value2" selected>Value 2</option>
If you care about XHTML validation, use selected="selected" - refer to this answer for more information.
<option value="value2" selected="selected">Value 2</option>
From the examples section of the MDN documentation for <select>, the following HTML is listed:
<!-- The second value will be selected initially -->
<select name="select"> <!--Supplement an id here instead of using 'name'-->
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Rendering a select list with PHP
To achieve this with the PHP code, the selected attribute needs to be conditionally added to the option.
First, before the while loop, store the selected location in a variable:
$selectedLocation = '';
if (isset($_POST['location'])) {
//Get selected value from values submitted with form
//use $_GET if form is submitted via GET
$selectedLocation = $_POST['location'];
}
Then in the while loop, set that selected attribute when the matching option is found (i.e. when $selectedLocation == $row['description']).
while($row = mysqli_fetch_assoc()){
$selected = ''; //default to empty string - not selected
if ($selectedLocation == $row['description']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['description']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
See a demosntration of this in this phpfiddle.

Edit and try:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>

Related

PHP - populate a select drop down from MySQL DB and have that field auto-populated in a form

I am trying to accomplish two things with the code below. Firstly I want my select options to be populated form my database. Secondly I want the field in the form to have the stored value selected on page load (like in a profile for a member). The way I have implemented below works, kind of, but I have two problems. Firstly if you open the dropdown then the selected option appears twice (once at the top and once in its normal position). Secondly if it is a required field then the user has to open the dropdown and select it again, even though it is appearing in the field (horrible ux). If it is not a required field the form acts as if nothing is selected and I get a Undefined index error further down the line. I am very sure there is a better way to implement what I am trying to achieve that wont give me these problems... all help greatly appriciated.
<?php
$query6 = "SELECT catname FROM travisor_catagory";
$result6 = mysqli_query($conn, $query6) or die(mysqli_error($conn));
$queryread3 = "SELECT * FROM travisor_catagory WHERE id = $catagory";
$result3 = mysqli_query($conn, $queryread3) or die(mysqli_error($conn));
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
$cat = $row["catname"];
}
}
echo "<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<option disabled selected value> $cat </option>";
if (mysqli_num_rows($result6) > 0) {
while ($row2 = mysqli_fetch_assoc($result6)) {
$catagory2 = $row2["catname"];
echo "<option>$catagory2</option>";
}
}
echo "</select>"
?>
Don't mix things up so much.....
When you get into larger programs, you will get lost really quickly, so K.I.S.S.!!!
You can 'jump' in/out of HTML and back to PHP to echo the $options variable, then back to HTML to complete the select. (this is my description of it when I teach newbies - this concept of 'jump in/out' works for PHP, HTML, JS - well any languages that you can combine in one page... - it is worth grasping the concept!)
First, get the options you will need with ONE query (watch how we take care of the selected one as well) - this will make a 'packet' of data in the $options variable.
<?php
// declare some values that we'll use later
$options = '';
// gather the data for the options
$sql = "SELECT id, catname FROM travisor_catagory";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$selected = '';
if($category == $row['id']){
$selected = "selected";
}
$options .= '<option ' . $selected . ' value="' . $row["id"] . '">" . $row["catname"] . "</option>";
}
}
// now we will 'jump' out of PHP and back to HTML
?>
<!-- we are in HTML, so comments and language changed... -->
<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<!-- here we 'jump' out of HTML and into PHP to use the $options variable -->
<?php echo $options; // and back out of PHP to HTML... ?>
<!-- where we finish up our select and whatever other HTML things -->
</select>
</div>
That should take care of both your issues with what you had.....
BTW, it looks like you are using Bootstrap - if so, I HIGHLY recommend you check this out (changed my life about fighting with select boxes! :) Bootstrap Select

Set the default value of a dynamic select drop down list in php

I have a form in an edititem.php page that is used to edit an item. The idea is that from another page, the searchitem.php a user can click edit and is taken to the edititem.php page to edit the selected item. What I'm trying to do is that automatically the default values in the form elements are populated with the values of the item selected to edit (from the searchitem.php) so that the user finds the form populated and only needs to modify the necessary value/s.
I'm passing all the required variables to the edititem.php and I am able to poulate all the input tags but I have a problem with the select tag which is not being set with the desired value. The select tag is being populated dynamically from a mysql database.
<label>Category:</label>
<select name="category">
<?php
$selectedCategory = '';
if (isset($_POST['category'])) {
$selectedCategory = $_POST['category'];
}
$sql_cat = "SELECT id, description FROM category ORDER BY description ASC";
$result_cat = mysqli_query($connection, $sql_cat);
if(mysqli_num_rows($result_cat) > 0){
while($row = mysqli_fetch_assoc($result_cat)){
$selected = '';
if ($selectedCategory == $row['id']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['id']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
With the above code the items in the select tag are being populated dynamically from a table and also if the page is refreshed the selected item is maintained as the selected value.
However I cannot set the default value when I press the edit item from the searchitem.php. The last value in the table is being displayed as default. Any ideas how I can achieve this since I cannot figure out how to do it. Note that all the variables are being passed successfully to the edititem.php page I just need to set the default value of the select drop down list as per the passed variable while keeping the select drop down list dynamic.

Filling an HTML drop down box from database using php, but I'm missing one record

I'm pulling rows from a mysql database to fill a drop down box. It works, but it misses out one option. I think it might be due to the fact I'm using the <optgroup> tag in the middle, where the option would be - in fact if I remove this, the whole list is printed.
My database has data similar to below:
Module Code|Module Name
-----------|-------------
SE1AA11 |Animal Acting
SE1BB11 |Boring Billiards
... | ...
SE2AA11 |Animal Archery
SE2BB11 |Boring Boxes
... | ...
(... indicates more data and yes, the module names are made up)
When the page loads, it misses out the first of the SE2 options. Any ideas why? Any help would be appreciated. Code below:
<select name="module1" id="module1" style="display: none;">
<option value="" selected disabled>Module 1</option>
<?php
$sql = "SELECT * FROM Modules";
$result=mysqli_query($con,$sql);
echo '<optgroup label="Part One">';
while (($row = mysqli_fetch_array($result)) &&
(substr($row['ModuleCode'], 0, -4) == "SE1")){
$code = $row['ModuleCode'];
$name = $row['ModuleName'];
echo '<option value="'.$code.'">' . $name . '</option>';
}
echo '</optgroup>';
echo '<optgroup label="Part Two">';
while (($row = mysqli_fetch_array($result)) &&
(substr($row['ModuleCode'], 0, -4) == "SE2")){
$code = $row['ModuleCode'];
$name = $row['ModuleName'];
echo '<option value="'.$code.'">' . $name . '</option>';
}
echo '</optgroup>';
?>
</select>
You miss out one record because of this: when your first while loop has iterated over all SE1* records, it does another call to mysqli_fetch_array() which fetches the next record from your result set. This record does not comply with your second condition (it does not start with 'SE1') so PHP moves to the next while loop, where another call is made to mysqli_fetch_array() which will fetch the next record from your result set.
Because your first 'SE2*' item was already fetched by the first loop, but never processed by that loop, you will not see that record back in your dropdown list.

select id from the select gender dropdown list

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 option to update second select option based on mysql populated dropdowns

I am trying to create a smart form which will automatically limit the options available of a second drop down box.
Background:
I am creating a ticketing system and I would like for the user to select a site from the "Site Selection" drop down and then the "User Selection" drop down will only contain users linked to the site selected on the first drop down, all information populated from MySQL.
Future:
I would then like to list all the services associated to that user with tick boxes under "Select Affected Services"
My js is pretty poor. So far I have been able to find some code by searching here that has allowed me to write the User's Computer ID into a text field. But I cannot figure out how to capture the output and query for the Computer Name (different table) and display that as a tick box option or to use the same method to limit the next lot of selection boxes. All code listed below I have not cleansed yet, alpha phase.
I realise that I could do this in steps using PHP only, but I am trying to pretty up my coding here and there.
Displaying Drop Downs:
<h3>Assign Site</h3>
<select id="site_add" name="site_add" style="width:217px; height:20px !important;">
<option value="-1"></option>';
$o = "SELECT * FROM company_sites WHERE company_id = " . $company_id . " ORDER BY sitename";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
echo '<option value="' . $r['id'] . '">' . $r['sitename'] . '</option>';
}
<h3>Assign User</h3>
<select id="comp_add" name="comp_add_1" style="width:217px; height:20px !important;">
<option value=""></option>';
$o = "SELECT * FROM company_staff WHERE company_id = " . $company_id . " ORDER BY id DESC";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
$user_computer_id = $r['computer_id'];
echo '<option value="' . $r['id'] . '">' . $r['firstname'] . ' ' . $r['lastname'] . '</option>';
}
Current JS to output selected user's computer ID into text field:
<script type="text/javascript">
window.onload=function() { attachBehaviors(); };
//
function attachBehaviors() {
document.getElementById(\'person\').onchange=function() {
loadUser(this.options[this.selectedIndex].value); // <-- check this, may be incorrect
}
}
function loadUser(optionvalue) {
// Always set a default
if (optionvalue==\'\') {
return;
}
opts = optionvalue.split(\':\');
var name = opts[0];
var email = opts[1];
document.getElementById(\'computer_id\').value=name;
}
</script>
<select name="person" id="person">
<option value=""></option>';
$result=mysql_query("SELECT * FROM company_staff");
while($row=mysql_fetch_array($result)) {
$submit_firstname = $row['firstname'];
$submit_lastname = $row['lastname'];
$submit_staff_id = $row['id'];
$submit_computer_id = $row['computer_id'];
echo '<option value="' . $submit_staff_id . '">' . $submit_firstname . ' ' . $submit_lastname . '</option>\n';
}
echo '
</select>
<input type="text" id="computer_id" name="name" placeholder="name" />
';
Any recommendations on how to achieve this would be greatly appreciated!
Thanks in advance!
You need AJAX, it's a combination of PHP and JS. ( javascript request data from the server, php processes the request, returns data ).
You would need to practice AJAX a bit to understand how to make this select box.
This is process in theory:
You output your first select box with PHP.
Make an onchange event handler for it that would call a server for information.
..options..
This updateNewDropDown function will take the value form a server response you selected and fetch the new data via PHP for the second select menu, and create the new select menu with the data AJAX response provided.
AJAX TUTORIALS:
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/ajax/default.asp

Categories