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
Related
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.
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.
I have a drop down form item with four options.
<p>Priority:
<select required name=\"priority\">
<option default value=\"1\">1 - 10 days</option>
<option value=\"2\">2 - 5 days</option>
<option value=\"3\">3 - 48 hours</option>
<option value=\"4\">4 - 24 hours</option>
</select>
</p>
http://jsfiddle.net/2nmxN/
These values are already stored in the SQL database with either 1,2,3,4. The page I am working on is an edit page of sorts, so I would like to have whichever value is set in the database be selected on the drop down, so the user does not have to reselect the value upon submission. How can I get it to find the value and select the correct option depending what is set? I have no problem doing this with a text field like this:
echo "<p>Cost: <input required type=\"text\" name=\"cost\" value=\"".$cost."\">";
Do I have to do four different if statements for each value (if ($priority == 1) {...}) etc.?
If the options were stored in an associative array, you could write something like:
foreach ($options as $value => $label) {
echo '<option value="', $value, '"', ($dbValue == $value ? ' selected="selected"' : ''), '>', $label, '</option>';
}
You do not have to do four different if statements for each value. You have to do four if statements, one for each value.
foreach ($options as $value => $label)
{
if(isset($_POST['priority']) && $_POST['priority']==$value)
{
$selected = 'selected="selected"';
}
else
{
$selected='';
}
echo '<option value="'. $value. '" '.$selected.'>'. $label. '</option>';
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - PRE-select drop down option
I have a situation in my php project where a user can edit his account.
In editing, there is a city field which is a drop down list of cities.
I want to already select one city which is in profile before editing(the one which user enter at the time of registration).
Also he is able to change his city by choosing fron drop down list.
Html code:
<div class="search_bar1_txt">State:</div>
<div class="search_bar1">
<select class="styled" name="state_trainer">
<option>-select-</option>
<option>washington</option>
<option>perth</option>
<option>delhi</option>
<option>london</option>
</select></div>
</div>
on editing I am using this code to fetch current data(city) of user:
<?php
if(isset($_GET['userid']))
{
$sql = "select city from `wp_pelleresuser` where userId =".$_GET['userid'];
$result = mysql_query($sql);
$value = mysql_fetch_assoc($result);
}?>
please tell me how can I get already selected one option which is fetch from database.
And also it is changeable.
<div class="search_bar1_txt">State:</div>
<div class="search_bar1">
<select class="styled" name="state_trainer">
<option <?if($value['city']=='-select-') echo "selected";?>>-select-</option>
<option <?if($value['city']=='washington') echo "selected";?>>washington</option>
<option <?if($value['city']=='perth') echo "selected";?>>perth</option>
<option <?if($value['city']=='delhi') echo "selected";?>>delhi</option>
<option <?if($value['city']=='london') echo "selected";?>>london</option>
</select>
</div>
</div>
You can do it in a number of ways, the simplest (and probably least elegant) is to do something like this:
<select class="styled" name="state_trainer">
<?php
$myCity='london'; // assumed to be data from database...
echo '<option'.($myCity=='-select-') ? ' selected ' : ' ' .'-select-</option>';
echo '<option'.($myCity=='washington') ? ' selected ' : ' ' .'washington</option>';
?>
This is of course horrid.
I would rather suggest that you check the data as you are pulling your information out of the database and putting your initial dropdown list together.
If you are making an array of data to create the drop down list (for example) check it right there and then. If the city matches what you want, do it inside your loop right off the bat.
$usersCity="london";
$myCityList=array();
while( ... ) // Database loop that is pulling the data from the database.
{
$selected='';
if($userCity==$row['city'])
{
$selected=' selected ';
}
$myCityList[]='<option'.$selected.'>'.$row['city'].'</option>';
}
Then to display the drop down list, you can simply do this:
$cityCount=count($myCityList);
for($i=0;$i<$cityCount;$i++)
{
echo $myCityList[$i].'\n';
}
The users city will already be selected.
I'm not sure if it is clear way but you can put code inside every option cell like this:
<option <?php if($value['city'] == "washington") echo "selected=selected"; ?> >washington</option>
This way you can get what u want.
And better use mysqli function for database interactions.
<option
<?php if ($value['city'] == delhi)
{
echo "selected = true";
} ?>
>delhi
</option>
Just het the selected value form db like
$choosen = $some value form db
then
$options = array(1 => 'data1', 2 => 'data2', 3 => 'data3');
foreach ($options as $key => $value)
{
echo '' . $value . '';
}
to get your selection box in php.I thnk you understand,it works for me