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>
Related
How can I retrieve selected value after form submision inside looped HTML select? I managed to solve the problem with manual if statements, but thats not dynamic.
I'm also storing previously submited value inside a cookie. I use self page form submit.
I managed to retrieve previous value from radio button:
<input type="radio" name="spol" value="moški" checked="checked" <?php if (isset($_POST['spol']) && $_POST['spol'] == 'moški') {
echo ' checked="checked"';
} ?>>
But can't find a way to do this inside foreach loop
<!---Cookie "keks" is storing previous submited string-->
<select name="status">
<?php
$_COOKIE['keks'];
$statusi = ["Dijak", "Študent", "Zaposlen", "Brezposelni"];
$counter= 0;
foreach ($statusi as $status) {
$counter++;
if ($counter == 2) {
echo "<option value=" . $status . " selected>" . $status . "</option>";
} else {
echo "<option value=" . $status . ">" . $status . "</option>";
}
}
?>
</select>
As stated in html comment, $_COOKIE['keks']; is storing the last value.
You might want to store that value into a variable or use it as is. and then, compare it against the current iteration of your loop.
$lastValue = $_COOKIE['keks'];
// some code
foreach ($statusi as $status)
{
if ($status == $lastValue)
// mark the option as selected
else
// don't mark it
}
when i click the edit button it should go the edit page
when i want to edit the row with coursename="php" in the drop down the course name should have selected as php since the course name and the paper name,paper description are present in the different table i cant select the particular value in drop down
if(isset($_GET['id'])) {
$table="papers";
$condition="paper_id=".$_GET["id"]."";
$select=selectlist($table,$condition);
$row=$list->fetch_array();
$table="courses";
$datalist=selectdata($table);
$data=Selectdata($table);
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
}
}
?>
i have tried the above code i know the problem is with the "selected" please help me
You are almost close to the answer.
Some modifications and you are done.
You need to compare two values.
The value from database (selected value) and the value in loop.
Another suggestion is that we should not write any logic inside any
HTML tag.
HTMLs/Templates are just for printing output to screen.
We should first evaluate all conditions and then print HTML.
selected Reference
Change
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
To:
$selected = ($row1['course_id'] == $courseid) ? 'selected="selected"' : '';
echo '<option value="'. $row1['course_id'].'" ' . $selected . '>'.$row1['course_name'].'</option>';
Replace your while loop:
<?php
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
if($courseid == $row1['course_id']) {
echo '<option value="'. $row1['course_id'].'" selected>'.$row1['course_name'].'</option>';
} else {
echo '<option value="'. $row1['course_id'].'" >'.$row1['course_name'].'</option>';
}
}
?>
You can do it as following:
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
$selected="";
if($row['course_id']==$course_id)
{
$selected="selected";
}
echo '<option value="'. $row1['course_id'].'" $selected>'.$row1['course_name'].'</option>';
}
This makes your job done
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
echo "<option value = '{$row1['course_id']}'";
if ($courseid == $row1['course_id'])
echo "selected = 'selected'";
echo ">{$row1['course_name']}</option>";
}
Try this (use ternary operator inside option)
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
change into
<option value="<?= $row1['course_id'] ?>" <?= $row1['course_id']==$courseid? "selected":""?> > <?= $row1['course_name'] ?> </option>';
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>";
}
?>
Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values.
I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it.
How can I achieve my selection being remembered?
Thanks for reading.
You'll need to use the name of your select field in place of "your_select_field_name" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
HTML does not have memory. The item that's selected by default in a <select> form element is the one with the selected attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.
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.