I have recursion function which populates data on my select drop down.
How can I pass a value that, if it matches with any value on drop down, gets selected?
this is function on my model:
function get_all_cat($parent,$level=0,$s){
$ui = '';
$this->db->order_by($this->id, $this->order);
$this->db->where('parent',$parent);
$query=$this->db->get($this->table)->result();
foreach ($query as $qu) {
if($s==$qu->id){
$y = 'selected';
}
$repeat = str_repeat('--', $level);
$ui .= '<option value="'. $qu->id .'" '.$y.' >' .$repeat. $qu->title.'</option>';
$new_level = $level+1;
$ui .= '' .$this->get_all_cat($qu->id,$new_level) .'';
}
return $ui;
}
and here is my select option in the view:
<div class="form-group">
<select name="category" class="form-control chosen-select">
<option value="">Any Category</option>
<?php
$cat = $this->Dbc_categories_model->get_all_cat(0,0,$this-session->userdata('clicked_id');
echo $cat;
?>
</select>
</div>
few notes that I pick up...
1.) Don't ever use variable names like $s => easy to lost track and that name doesn't tell you what variable contain or do
2.) You're not passing selected value to reclusive function (missing third parameter)
Otherwise looks like this are working code.
Related
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>';
}
}
?>
This is sort of an extension of the problem solved here: Set default value for HTML select control in PHP however I would like to fill in Multiple values that match, with the values to fill in stored in an additional array:
This is my code so far:
<select name="genres[]" id="genres_edit" multiple>
<?php
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
for($i = 0;$i < count($genrelist);$i++) {
echo "<option value=\"$genrelist[$i]\"";
for ($g = 0; $g < count($genre);$g++) {
if ($genrelist[$i] == $genre[$g]) {
echo "selected=\"selected\"";
}
echo ">$genrelist[$i]</option>";
}
}
?>
</select>
$genrelist is the array of all possible genres that will be used to fill up the select control, and the array of actual genres is stored in $genre.
Basically I want it to highlight the values in the selectbox that match any of the values in the $genre array.
i.e. if the genres stored in $genres are: Adventure, Cooking, Western, then those 3 values will be highlighted in the select box, out of the 6 available genres in the box.
Here's how I'd do it ...
$genres = array(
'Action',
'Western'
);
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
foreach ($genrelist as $k=>$v) {
$sel = (array_search($v,$genres) !== false) ? ' selected' : '';
echo '<option value="'. $k .'"'. $sel .'>'. $v .'</option>';
}
Here's the sandbox ... http://sandbox.onlinephpfunctions.com/code/e4f2ca28e0fd43513b694f5669329cc1db328598
Assuming your form in being set with method="get" then the $_GET superglobal should have an array in it called genres (as defined by the fact that your multiple select box is called genres[]).
So when looping through your output you should be able to check if the current genre (from the $genrelist array) exists in the $_GET['genres'] array ... like so:
<?php
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
?>
<select name="genres[]" id="genres_edit" multiple="multiple">
<?php foreach($genrelist as $genre): ?>
<?php $sThisSelected = in_array($genre, $_GET['genres']) ? " selected=\"selected\"" : ""; ?>
<option value=\"<?= $genre; ?>\"<?= $sThisSelected; ?>><?= $genre; ?></option>
<?php endforeach; ?>
</select>
There's no sanity checking or sanitisation in this but that's the theory anyway.
If you want multiple selection you must specify your select tag with multiple option
<select multiple="1">
<option selected>option1</option>
<option selected>option1</option>
<option selected>option1</option>
</select>
The drawback is that the select menu is no more a dropdown, if that matter for you, let me know and I will try to tune in the solution.
How would I go about setting the "selected" attribute to one of these boxes, based on what value is stored in the $genre variable?
i.e. If $genre == "Puzzle" then
<option value=Puzzle>
becomes
<option value=Puzzle selected>
Here is my current code:
<?php
$query = "SELECT * FROM release_dates WHERE id = $id";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$genre = $row['game_genre'];
?>
<select name=genre>
<option value=Action>Action</option>
<option value=Adventure>Adventure</option>
<option value=Puzzle>Puzzle</option>
<option value=RPG>RPG</option>
<option value=Horror>Horror</option>
<option value=Shooter>Shooter</option>
<option value=Simulator>Simulator</option>
<option value=Sport>Sport</option>
<option value=Strategy>Strategy</option>
</select>
Also, for extra brownie points, how would this apply to select boxes with the "multiple" attribute?
Any help or ideas would be greatly appreciated.
Well, that's pretty simple actually:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
Just use a ternary operator (condition) ? true:false to input "selected" if the value is set. Simply duplicate that logic on all the options:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
<option value=Adventure <?php $genre == "Adventure" ? "selected":""?> >Adventure</option>
<option value=Puzzle <?php $genre == "Puzzle" ? "selected":""?> >Puzzle</option>
<option value=RPG <?php $genre == "RPG" ? "selected":""?> >RPG</option>
Hope that helps!
You could use a foreach loop to iterate over your options, and each time, perform a check using an if statement to see if it matches:
foreach ($genres as $genre) {
if ($genre === "Puzzle") {
echo '<option value="'.$genre.'" selected>'.$genre.'</option>';
else {
echo '<option value="'.$genre.'">'.$genre.'</option>';
}
}
By the way, you shouldn't be using mysql_* functions anymore as they are unsafe, deprecated, and will be removed from PHP in the future. Take a look at PDO.
<option value="Strategy" <?php if($genre == "Strategy"){ echo 'selected="selected"';} ?> >Strategy</option>
I came up with a version that keeps everything in PHP
<?php
$query = "SELECT * FROM release_dates WHERE id = ". $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
// possible options
$genre_options = array(
'Action'
'Adventure'
'Puzzle'
'RPG'
'Horror'
'Shooter'
'Simulator'
'Sport'
'Strategy'
);
// loop over the options, and wrap them in tags
$options = '';
foreach ($genre_options as $genre) {
// check if we have a match
$selected = '';
if ($genre == $row['game_genre']) {
$selected = 'selected="selected"';
}
$options .= '<option value="'. $genre .'" '. $selected .'>'. $genre .'</option>'
}
echo '
<select name=genre>
'. $options .'
</select>
';
?>
What this does is create an array of possible genre's, loop over them, and see if any of them match the genre that was returned from the query. If thats the case it will add the selected="selected" attribute.
Unfortunately I'll be missing out on the "brownie points", because I'm not able to help you with the multi-select.
Let me know if this helps!
EDIT: I also noted that in your query you where passing the $id variable as a string. Fixed that in the query in my example.
Instead of defining your genres using plain HTML, create an array with all your genres.
To do so:
$genres = array(
"Action",
"Adventure",
"Puzzle",
"RPG",
"Horror",
"Shooter",
"Simulator",
"Sport",
"Strategy"
);
foreach($genres as $currentGenre) {
echo "<option value="'.$currentGenre.'" '.($currentGenre == $genre ? "selected" : "").'>'.$currentGenre.'</option>';
}
What this does, is loop over all your genres and create a single <option> for each of them. If the $currentGenre (so one of the genres from the array $genres) matches $genre (which you pulled from MySQL), it selects that option using a inline if-statement.
I have a select control that will load next to each user and the value defaults to which floor that user is located on based on the result from the MySQL Database. Whomever is editing the list can change which floor that user is located on and submit the change to push to the database. However when I receive the $_POST['selFloor'] value it is always whichever the default selected value is. No matter if the user changes it or not.
<?php
$floors = array('1st'=>"First",
'2nd'=>"Second",
'3rd'=>"Third",
'4th'=>"Fourth",
'5th'=>"Fifth",
'6th Control'=>"Sixth");
$query = "SELECT * FROM employees ORDER BY name asc";
$result = $db->query($query);
$i = 0;
while ($row = $result->fetch_array())
{
$i++;
echo '<select name="field['.$i.'][floor]"';
foreach($floors as $key=>$val) {
echo ($key == $row['floor']) ? "<option selected=\"selected\" value=\"$key\">$val</option>":"<option value=\"$key\">$val</option>";
}
echo '</select>';
} ?>
A sample of the select control. If the $row['floor'] returns ['1st'] it will make that option the selected value, but once the user changes it to '2nd' and hits submit, $_POST only see's the select value for whichever option has the selected argument.
foreach ($_REQUEST as $key => $val) {
if (is_array($val)) {
foreach($val as $subkey => $sub) {
echo $sub['floor'] // Outputs first option that got selected set
}
}
}
HTML Output of Select:
<select name="field[1][floor]">
<option value="1st">First</option>
<option value="2nd">Second</option>
<option selected="selected" value="3rd">Third</option>
<option value="4th">Fourth</option>
<option value="5th">Fifth</option>
<option value="6th">Sixth</option>
</select>
Thanks.
I don't see any errors in your HTML, except for the fact, that you are checking $_POST['selFloor'], while the name of select is field[1][floor]. Try to change it to 'selFloor':
echo '<select name="selFloor">';
...
And I don't see closing angle bracket (>) for select.
Because each one of your <option> menus has a selected attribute, the browser doesn't know which one is selected even though it is firing the change event.
Try placing the selected attribute on the first <option> only.
<?php
foreach($floors as $key=>$val) {
// if first, place selected attribute
echo ($key == $row['floor'])
? "<option value=\"$key\">$val</option>" // selected att was removed
:"<option value=\"$key\">$val</option>";
}
?>
here is my mysql and php code layout:
I have 3 tables
tableA stores unique "person" information
tableB stores unique "places" information
tableC stores not unique information about a person and places they have "beenTo".
here is how i layed out my form:
-one big form to insert into "person" tableA; "beenTo" tableC
in the form, a person mulitple selects "places" which get inserted into "beenTo"
my question is, when i am editing a "person" how do i display what the user has already selected to appear on my multiple select options drop down menu?
my drop down menu at the moment query "places" table and displays it in a multiple select drop down menu. its easier when a person have beenTo one place, the problem arrises when there is more than one "beenTo" places?
Foreach option, check if they have beenTo it. Then add the selected="selected" attribute to the tag if true.
Example:
<select multiple="multiple">
<option selected="selected">Rome</option>
<option>France</option>
<option selected="selected">Underpants</option>
</select>
And in PHP this might look like:
$beenTo = array("Rome","Underpants");
$places = array("Rome","France","Underpants");
?> <select multiple="multiple"> <?php
foreach($places as $place) {
echo "<option";
$found = false;
foreach($beenTo as $placeBeenTo) {
echo "value='$place'";
if ($placeBeenTo == $place) {
$found == true;
echo " selected=\"selected\" ";
break;
}
}
if (!$found) echo ">";
echo $place . "</option>";
}
?> </select> <?php
There's probably a much more efficient way to do this.
For clarification, you will want to have a name attribute for your select tag which allows for multiple selected options to function correctly.
<form method="post" action="">
<select name="places[]" multiple="multiple">
<?php
$_POST += array('places' => array());
$places = array('fr' => 'France', 'cn' => 'China', 'jp' => 'Japan');
$beenTo = array_flip($_POST['places']);
foreach ($places as $place => $place_label) {
$selected = isset($beenTo[$place]) ? ' selected="selected"' : '';
echo '<option value="' . $place . '"' . $selected . '>' . $place_label . '</option>';
}
?>
</select>
<input type="submit" value="Save Changes" />
</form>
<option id = 'example' <? if ($_POST['example']) echo 'selected' ?>>
But you'll be using a $_SERVER['cookies'] or other cache to store the past visits, not the $_POST array.. edit with extreme predjudice