I get some values from an old db of a client as such:
$query = "SELECT rowid,source FROM `".$table."`";
$result = mysql_query($query);$temp=0;$p = array();
while ($row = mysql_fetch_array($result)) {$p[$temp] = $row;$temp++;}
and then I loop through the values as such:
// loop through all possible values
foreach ($p as $obj) {
}
Inside the foreach loop I will print <option>
element and I want to determine the <option selected/>
elements. The selected elements could be more than 1, since its a multiselect form.
First thing I check whether a $selected
value equals to rowid.
// check if exists equals to rowid
if ($obj["rowid"] == $selected){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
This works just find if $selected = "1"
(or any single digit)
My problem and my question comes if $selected = "3,4"
. Then I need to loop through the values and separate the comma-separated values inside foreach ?
Here is my complete code:
$selected = "3,4";
$query = "SELECT rowid,source FROM `" . $table . "`";
$result = mysql_query($query);
$temp = 0;
$p = array();
while ($row = mysql_fetch_array($result)) {
$p[$temp] = $row;
$temp++;
}
// loop through all possible values
foreach($p as $obj) {
// check if exists equals to rowid
if ($obj["rowid"] == $selected) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
else {
// check if default exists with comma separated values
if (!empty($default) && strpos($selected, ',') !== false) {
$arr_values = explode(',', $selected);
// loop through comma-separated values to get the selected items
foreach($arr_values as $selected) {
if ($obj["rowid"] == $default) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
}
// $return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
else {
$return.= '<option value="' . $obj["rowid"] . '">' . $obj["source"] . '</option>';
}
}
}