Looping through a drop down, how to select value? - php

When displaying a form on a page for a user to edit information, and the form consists of a drop down box, how do you loop through the selections in the dropdown box to select their predefined mySQL entry?
For example
Users country: Australia
How would I go about searching through a list of countries ie: http://snipplr.com/view/4792/country-drop-down-list-for-web-forms/ to make:
<option value="AU">Australia</option>
become
<option value="AU" selected="selected">Australia</option>

You could do something like:
<?php
$countries = array('AU' => 'Australia', 'AF' => 'Afghanistan', ...);
$selected = 'AU';
foreach ($countries as $code => $label) {
echo '<option value="' . $code . '"';
if ($selected == $code) {
echo ' selected="selected"';
}
echo '>' . $label . '</option>';
}
?>
Not the prettiest but you get the idea. As Shakti suggests, it's also easier to maintain if the values are in the DB and not in a massive array in the middle of the code.

Could be something like this:
<?php
//your query here
$sql = "SELECT * FROM countries ORDER BY code ASC";
$result_set = $database->query($sql);
while($country = $database->fetch_array($result_set)) {
if ($country["code"] == "AU"){
echo "<option value=\"{$country['code']}\" selected=\"selected\">{$country['name']}</option>";
}
else {
echo "<option value=\"{$country['code']}\">{$country['name']}</option>";
}
?>

Related

Multi-select add selected attribute if the value is present in the main array - php

I am working with a multi-select and GET method.I want multiple options selected when the form is reloaded after submitted based on the $_GET method from url parametres.i have associated URL parametres is cuisine%5B%5D=indian&cuisine%5B%5D=thai.Actually multi-select is about cuisine.
And my codes are below:
<select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
<?php
$selected_cuisine = $_GET['cuisine'];
// Get all cuisines list by get_terms() function.Its built in wordpress
$restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
$cuisines = array();
foreach ($restaurant_cuisines as $restaurant_cuisine) {
// echo $restaurant_cuisine;
array_push( $cuisines, $restaurant_cuisine->slug );
// echo $cuisines_list;
}
print_r ($selected_cuisine);
print_r($cuisines);
if(array_intersect($selected_cuisine, $cuisines)){
$selected = 'selected';
}else{
$selected = '';
}
foreach ($restaurant_cuisines as $cuisine) {
echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
}
?>
</select>
But the problem is that every options is getting selected.Actually there is total 3 cuisines : indian, thai & chainese and 2 of them are selected -> indian and thai.But problem is 3 options are selected. :/
Remember when you are using array_intersect it is setting true is at least one match in both array.So everything is getting selected.Rather you can try this:
<select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
<?php
$selected_cuisine = $_GET['cuisine'];
// Get all cuisines list by get_terms() function.Its built in wordpress
$restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
$cuisines = array();
foreach ($restaurant_cuisines as $restaurant_cuisine) {
array_push( $cuisines, $restaurant_cuisine->slug );
}
foreach ($restaurant_cuisines as $cuisine) {
if(in_array($cuisine->slug, $selected_cuisine)){
$selected = 'selected';
}else{
$selected = '';
}
echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
}
?>

selecting option from select element with php

I have a database field country which I want to query and select that country option from a select element. Is there any way to do this without adding:
if (query->country == "<some country>"){echo "selected"}
in every single option tag? As there are hundreds of country options. Here is a little example of the code. Thank you.
$query = $query->fetch_object();
// which ever country is held in the variable `$query->country` should be selected
echo"<select>
<option>Afghanistan</option>
......
......
<option>Zimbabwe</option>
</select>";
Don't you have a list of all countries on your server?
$countries = ["Afghanistan", ... , "Zimbabwe"];
You could do something like this:
$selection = "Some country";
echo "<select>";
foreach($countries as $country)
{
if($country == $selection)
echo "<option selected>" . $country . "</option>";
else
echo "<option>" . $country . "</option>";
}
echo "</select>";
The IF still needs to be "placed" on every <option> but as a programmer you should do something like this:
$options = array( 'Afghanistan', '...', 'Zimbabwe' );
foreach( $options as $option )
{
$selected = ( $query->country == $option )? ' selected': '';
echo '<option' . $selected . '>' . $option . '</option>';
}
and if you're unfamiliar with ternary operator, the $selected = ... part above can be written like this:
if ( $query->country == $option )
{
$selected = ' selected';
}
else
{
$selected = '';
}

Country list selection box - Set one as selected

I have a country list of every country in a form to get a parcel quote.
When a user presses the "Get Quote" button, all the text forms retain the information previously entered using PHP.
How can I do this with the country list box? As I can't have PHP on every option checking if that is the country selected and adding "Selected" to the html.
Is there a better way other than generating the country list from a file in a loop?
EDIT:
Going for the method of looping through a file, and checking..
This is what I have so far:
$countries = fopen("includes/countries.txt", "r");
$countries = explode(";", $countries);
Then in the HTML:
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
echo("<option value=\"" . $country . "\">" . $country . "</option>");
}
?>
</select>
Not yet finished.
I assume you have an array with your countries stored. You could try something like this:
$countries = array('Albania', 'Egypt');
$selected_country_id = $_GET['c_id']; // You may need to change this to match with your code
$country_selected = array();
foreach($countries as $country) {
if($country['id'] == $selected_country_id) {
$country_selected[ $country['id'] ] = ' selected ';
} else {
$country_selected[ $country['id'] ] = '';
}
}
Then, assuming that you dynamically add your Select-Options, do this:
// In your each-fn
echo '<option value="' . $country['id'] . '" ' . $country_selected[ $country['id'] ] . '>' . $country['name'] . '</option>';
Something like this would be better
foreach ($countries as $country) {
?>
<option value="<?php echo $country" <?php echo ($country == $_POST['country'] ? 'selected' : ''; ?>><?php echo $country; ?></option>
<?php
}
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
if(isset($_POST["country"]) && $_POST["country"] == $country){
$sel = "selected";
}else { $sel= ""; }
echo("<option value=\"" . $country . "\"" .$sel.">" . $country . "</option>");
}
?>
</select>
Get All Country-State-City Selectbox ....!!!
See Link : GitHub

Select Combobox values in PHP with MySql Result

I am looking for some method to select a php combobox "<select>" based on results from mysql.
Actually I am working on a php form that will be used to edit existing values in mysql table. My first form will simply pass the id of the record to be edited, and this goes something like this Click to edit
Code on editCalendar.php is as follows:
<?php
include("dbpath.php");
$id = htmlspecialchars($_GET["id"]);
$sql="Select * from event_Date where eventid=" . $id;
$result=mysql_query($sql);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result))
{
$name=$row["EventTitle"];
$close=$row["OpenOrClose"];
$remarks=$row["Remarks"];
$date=$row["EventDate"];
$type=$row["Type"];
}
?>
The value obtained in $close will be used to select "SelectClosedOrOpen" on the same form, i.e. the user will get pre selected option from the populated list.
<select id="SelectClosedOrOpen">
<option value="3">Select</option>
<option value="0">Open</option>
<option value="1">Closed</option>
</select>
Means, if $close has 0, then <option value="0">Open</option> must be selected else if $close has 1 then <option value="1">Closed</option> should be automatically selected on formload.
You'll just need to write the selected attribute in there. Try this
<select id="SelectClosedOrOpen">
<option value="3" <?php echo ($close == 3) ? 'selected="selected"': ''; ?>>Select</option>
<option value="0" <?php echo ($close == 0) ? 'selected="selected"': ''; ?>>Open</option>
<option value="1" <?php echo ($close == 1) ? 'selected="selected"': ''; ?>>Closed</option>
</select>
I created this function some years back. I hope it helps you.
It basically requires an array of your options and the value of the option to be pre-selected. It returns the OPTIONS for your select, so you still have to create the SELECT tags, which allows you to customise the ID, JS etc..
function drop_down_box_options_from_array($choices,$default="")
{
$output= '';
// $choices is contructed using $choices[]=array("value","Displayed Choice");
while (list ($key, $val) = each ($choices))
{
$output.= '<option value="';
$output.= $choices[$key][0];
if ($default==$choices[$key][0])
{
$output.= '" selected="selected" >';
}
else
{
$output.= '">';
}
$output.= $choices[$key][1];
$output.= '</option>';
$output.= "\n";
}
return $output;
}
Using your scenario:
<select id="SelectClosedOrOpen" name="OpenOrClose">
<?php
// defined here for clarity, but can be defined earlier ie in a config file
$choices[]=array('3', 'Select');
$choices[]=array('0', 'Open');
$choices[]=array('1', 'Closed');
echo drop_down_box_options_from_array($choices, $row['OpenOrClose']);
?>
</select>

Refilling a select box with POST data (php)

I have a select box that shows 3 options: option1, option2, option3. When a user hits submit, then in $_POST I do have the value selected. Is there an easy way to redisplay the select box with the chosen option highlighted WITHOUT it being repeated in the options?
In other words, if option2 is selected and submit is clicked, the page should display again with option2 selected, and option1 and option 3 underneath.
Thanks.
<?php
$arrValues = array(...);
$selectedValue = (isset ($_POST['selectName']) ? $_POST['selectName'] : "");
?>
<select name="selectName">
<?php
for ($i = 0; $i < count($arrValues); $i++)
{
$opts = ($arrValues[$i] == $selectedValue) ? ' selected="selected"': '';
echo '<option value="' . $arrValues[$i] . '"' . $opts . '>' . $arrValues[$i] . '</option>';
}
?>
</select>
Create your options like this.
$options = array("optionvalue" => "Option Name");
foreach($options as $value => $name)
{
if(isset($_POST['select_box']))
{
if($_POST['select_box'] == $value)
{
echo '<option selected="selected" value="'.$value.'">'.$name.'</option>';
continue;
}
}
echo '<option value="'.$value.'">'.$name.'</option>';
}
When you generate the select box, use the POST data (if available) to pick the item that's selected (and/or to sort the items).
Kind of like:
if($_POST["optval"] == $opt) $sel = "selected='selected'"; else $sel = "";
print "<option value='$opt' " . $sel . ">$opt</option>";
Naturally you'd want to verify that the POST data is valid and that it exists (isset). Assuming of course that you generate your select box from data accessible by PHP, rather than statically define it.

Categories