Get selected dropdown option from database using PHP - php

I have a dropdown section menu that I need to set the selected value based on the database values.
I have a table with the following structure: id, pid, disporder, title, url
I am then using this code for the dropdown:
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
echo "<option value=\"".$parent['id']."\">".$parent['title']."</option>";
}
echo "</select>";
How would I go by getting the selected value based on what's in the database?
I have multiple entries in the table, so using an array with values (similar to this), isn't what I want to use:
$options = array('1', '2', '3');
foreach($options as $option)
{
if($option = $parent['id'])
{
echo "selected";
}
else
{
echo "";
}
Thanks.

You haven't really given enough info to really say what the exact solution would be. If you're creating a select tag in PHP though, the typical pattern for building the markup is:
<?php
$options = get_me_some_options();
$select_markup = '<select name="my-select" id="my-select>';
foreach ($options as $key => $val) {
$selected = '';
if (is_this_selected($val)) {
$selected = 'selected';
}
$select_markup .= "<option $selected val=\""
. $val['id'] . "\">" . $val['name'] . '</option>';
}
echo $select_markup . "</select>";
It looks like your use case is similar, but slightly more complex. Ultimately though what matters is that, inside the loop, you have some way to determine whether a given row should be 'selected' or not.

If I understand correctly, you want to compare each $parent['id'] with the values of an array called $options. Try this:
$options = array('1', '2', '3');
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
$selected = ( in_array($parent['id'], $options) ? ' selected' : '';
echo "<option value=\"".$parent['id']."\"$selected>".$parent['title']."</option>";
}
echo "</select>";

If you're trying to use this in multiselects then this might help
<?php
$optionsToSelect=array(1,2,3);
?>
<select name="parent" id="parent">
<?php
foreach($allOptions as $opt){
?>
<option value="<?php echo $opt['value'];?>" <? echo $opt['selected']==1?'selected="selected"':'';?>><?php echo $opt['optTitle'];?><option>
<?php
}
?>
</select>

Related

Input <select> selected is not working correctly in PHP by comparing 2 arrays

I have
3 <select></select>
with 8 options inside (Array_1 with 8 position). All options value are the same.
What i am trying to do is that I want to make the Value in Array_2 to be the Selected value.
However, looks like my loop is not working correctly.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
for($i=0;$i<count($array_2);$i++){
echo '<select name="product_header_image[]">';
for($b=0;$b<count($array_1);$b++){
if(in_array($array_2[$i],$array_1)){
echo '<option selected VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}else{
echo '<option VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}
}
echo '</select>';
echo '<br>';
}
Anyone know whats wrong with my coding? what I want to achieve is the right hand side of the screenshot.
You need to replace this check:
if(in_array($array_2[$i], $array_1)) {
...
}
on this:
if($array_2[$i] == $array_1[$b]) {
...
}
Demo here
Not sure I understand your scenario, but this might be what you are looking for. It generates a dropdown with all the elements from both arrays, and highlights the selected ones.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
echo '<select name="product_header_image[]" multiple>';
foreach ($array_1 as $elem1) {
echo '<option VALUE="'. $elem1 .'" >' . $elem1 .'</option>';
}
foreach ($array_2 as $elem2) {
$selected = '';
if( in_array($elem2, $array_1) ) $selected = 'selected ';
echo '<option '. $selected . 'VALUE="' . $elem2 . '" >'.$elem2.'</option>';
}
echo '</select>';
echo '<br>';

Replace Values of an array with key's of another array. PHP Homework

Hi there this is a bit hard to word so I'm trying my best to explain what is happening. Pretty much I have a form where I had a selection box. I had to fill it with the following.
<?
$PROVINCES = array("--" => "---Please Select Provinces---",
"nf"=>"Newfoundland",
"pe"=>"PrinceEdwardIsland",
"nb"=>"New Brunswick",
"ns"=>"Nova Scotia",
"qc"=>"Quebec",
"on"=>"Ontario",
"mb"=>"Manitoba",
"sk"=>"Saskatchewan",
"ab"=>"Alberta",
"bc"=>"British Columbia",
"nt"=>"Northwest Territories");?>
So I did that:
<select name = "province[]" multiple size = "12" <?if ($_SERVER['REQUEST_METHOD'] == 'POST'){if (isset($errorList['province']))
{
echo "class=\"error\"";
}}?>>
<?php foreach($PROVINCES as $key => $value) { ?>
<option value="<?php echo $key ?>"<?= (in_array($key, $_POST['province'] ) )?'selected':'';?>><?php echo $value?></option>
<?php }?>
</select>
Now the next step was to make a table of all the values in $_POST
but the problem is since the values are nf, pe, nb etc it will write those in the table and not PrinceEdwardIsland, New Brunswick, Nova Scotia.
echo '<table border="1" style="width:100%">';
foreach($_POST as $name => $out)
{
echo '<tr>';
echo '<td>';
echo '<strong>';
echo strtoupper($name);
echo '</strong>';
echo '</td>';
echo '<td>';
if (is_array($out))
{
count($_POST);
$arrayOutput = implode(", ", $out);
echo $arrayOutput;
}
else if (strlen($out) <= 0)
{
echo "---None supplied---";
}
else
{
echo $out;
}
echo '</td>';
echo '</tr>';
}
echo '</table>';
But as you can see from here we have multiple different $name from $_POST when we call it in our foreach loop.
And as you can see when I do is_array($out) I implode the array and split it out by ","'s I only need to get the full names for provinces, I had a checkbox for Status and it only has to display what the value in the checkbox was. I'm trying to figure out how I can get the $key of $PROVINCES to replace the imploded values in $_POST['province']
Hopefully I explained it well enough for people to understand.

Multiple Select box from2 Arrays

How can i create a Multiple select box from 2 arrays
1st array contains all values and the second array contains the values that will be marked as selected in multiple select
$a=array[1,2,3,4,5,6,7,8];
$b=array[3,7,8];
the multiple selectbox will have all the values from array $a but values from array $b will be selected.
Any way to achieve this ?
You can use this code
$a=array(1,2,3,4,5,6,7,8);
$b=array(3,7,8);
$selected="";
foreach($a as $val)
{
if(in_array($val,$b))
{
$selected = 'selected="selected"';
}
//Code for create multi select drop down and echo $selected in option like
<option $selected value="" ></option>
}
$a=array(1,2,3,4,5,6,7,8);
$b=array(3,7,8);
$html = '<select multiple>';
foreach($a as $val)
{
$selected = (in_array($val,$b)) ? 'selected' : '';
$html .= '<option value="' . $a . '"' . $selected . '>' . $a . '</option>';
}
$html .= '</select>';
echo $html;

how to retrieve values from a table which are stored in a colomn

How can I retrieve the values from a table which I stored in a column using a text box by comma separated.
Like:
Enter Member Names: [raj, ram, john, mop]
It has been stored in a column as this is [raj, ram, john, mop]; on site I want it in a select option:
Select Member:
<option>raj</option>
<option>ram</option>
<option>john</option>
<option>jonh</option>
Option will be so on, how to resolve it. any query to retrieve this type of data
you work like this
$query=mysql_fetch_assoc(mysql_query("select * from table_name"));
$exp=explode(",",$query['col_name']);
foreach($each as $exp)
{
?>
<option value="<?php echo $each[0];?>"><?php echo $each[0];?></option>
<option value="<?php echo $each[1];?>"><?php echo $each[1];?></option>
<option value="<?php echo $each[2];?>"><?php echo $each[2];?></option>
<option value="<?php echo $each[4];?>"><?php echo $each[3];?></option>
<?php
}
Try to use
<?php echo '<select name="name">';
$list = explode(',', $value);
foreach ($list as $item)
{
echo '<option value="' . $id . '">' . $item . '</option>';
}
echo '</select>';
$query = "SELECT member_name FROM users";
// after getting the result
$resultArray = explode(",",$ft['members']); // $ft['members'] is "raj, ram, john, mop"
foreach($resultArray as $value) {
echo $value;
echo "<br>";
}

Populate drop down list from database

I`m using this code to repopulate drop down list from the database :
$city_id = 15;
while($row = mysql_fetch_assoc($result)) {
$selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';
}
It`s work like a charm but my question is are they more elegance solutions ?
Other than improving the indentation of the code, this is fine.
$city_id = 15;
while($row = mysql_fetch_assoc($result))
{
$selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}
Well, a more elegant solution would be to have a "controller" file that fetches all the cities an puts them into an array/object list/whatever. Then, in a "view" file, you iterate over that variable. That way, you separate a bit more the presentation from the logic.
In view:
<select name=student value=''>Student Name</option>
<?php foreach($cities as $city): ?>
<option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
<?php endforeach; ?>
</select>
Also, I'd highly recommend using PDO for DB access.
I always use a function, since select boxes are something I end up creating a lot...
function select($name, $default, $values, $style='', $param='') {
$html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
foreach($values as $i => $data) {
if (isset($data['noFormat'])) {
$html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
} else {
$html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
}
}
$html .= '</select>';
return $html;
}
Then loop through your query to build the array like this:
$default[] = array('value' => '0', 'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {
$list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);
And finally an example to create the HTML:
select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');
Hope it helps!
mysql_fetch_assoc to mysql_fetch_array
add proper comments
use standard php class ezsql or simple class tuts
$query="SELECT name,id FROM student";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";//Closing of list box

Categories