So I created a function that will pull the values from an enum field in my database:
<?php
function set_and_enum_values( &$conn, $table , $field )
{
$query = "SHOW COLUMNS FROM `$table` LIKE '$field'";
$result = mysqli_query( $conn, $query ) or die( 'Error getting Enum/Set field ' . mysqli_error() );
$row = mysqli_fetch_row($result);
if(stripos($row[1], 'enum') !== false || stripos($row[1], 'set') !== false)
{
$values = str_ireplace(array('enum(', 'set('), '', trim($row[1], ')'));
$values = explode(',', $values);
$values = array_map(function($str) { return trim($str, '\'"'); }, $values);
}
return $values;
}
?>
I am executing this function in a HTML form, and it's working like a charm to pull the values and list them in a drop down. Here is what I'm using:
<td><select name="owner">
<?php
$options = set_and_enum_values($con, 'inventory', 'owner');
foreach($options as $option):
$selected = (isset($row['owner']) && $row['owner'] == $option) ? ' selected="selected"' : '';
?>
<option><?php echo $selected; ?><?php echo $option ?></option>
<?php endforeach; ?>
</select></td>
However, I am unable to figure out how to make the default (aka, SELECTED) value show as the default in the drop down. What I have right now will rename the current used value selected=<value1>
, but it doesn't make it the default. Can anyone assist? Does my question make sense?
Thanks!
EDIT: Here is the working code, now that I've fixed my syntax error:
<td><select name="owner">
<?php
$options = set_and_enum_values($con, 'inventory', 'owner');
foreach($options as $option):
$selected = (isset($row['owner']) && $row['owner'] == $option) ? ' selected="selected"' : '';
?>
<option<?php echo $selected; ?>><?php echo $option ?></option>
<?php endforeach; ?>
</select></td>
To select one ore more items in the select element you only have to put the "selected" inside the element like:
here the Snipey (value=3) is selected.
So in your example it have to be inside the ... maybe it was only a typo:
Tom, oe1tkt