Forum Moderators: coopster

Message Too Old, No Replies

Is this OK == enum 1 array 0 problem

enum 1 array 0

         

Gruessle

9:44 am on Mar 30, 2005 (gmt 0)

10+ Year Member



I am using function getEnumOptions($table, $field) to pull the enum options from my table!
Works really good.
This is the array I get:

Array
(
[0] =>
[1] => mid
[2] => best
[3] => average
)

But here in my select options ass you can see I have to add this: $abbrev++; to make it work.
I guess enum does not start with 0 it starts with 1.
Is this OK the way I am doing this?

$i = 1;
foreach ($TypeA as $abbrev => $full)
{
$abbrev++;
if ($full == TypeB) {
echo "<option value='$abbrev' selected>$full</option>";
} else {
echo "<option value='$abbrev'>$full</option>";
}
$i++;
}

function getEnumOptions($table, $field) {
$finalResult = array();

if (strlen(trim($table)) < 1) return false;
$query = "show columns from $table";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)){
if ($field!= $row["Field"]) continue;
//check if enum type
if (ereg('enum.(.*).', $row['Type'], $match)) {
$opts = explode(',', $match[1]);
foreach ($opts as $item)
$finalResult[] = substr($item, 1, strlen($item)-2);
}
else
return false;
}
return $finalResult;
}

coopster

11:38 pm on Mar 30, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You are correct, each enumeration value has an index and the values from the list of allowable elements in the column specification are numbered beginning with 1. See The ENUM Type [dev.mysql.com] for more information. I assume you must have a blank value defined for the first value in your ENUM column type as well, correct? Otherwise, index 0 would not be coming back blank like that. OK, well then what I would do is actually build the array starting at index 1:
function getEnumOptions($table, $field) 
{
$finalResult = array();
$count = 1;
if (strlen(trim($table)) < 1) return false;
$query = "show columns from $table";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
if ($field!= $row["Field"]) continue;
//check if enum type
if (ereg('enum.(.*).', $row['Type'], $match)) {
$opts = explode(',', $match[1]);
foreach ($opts as $item) {
$finalResult[$count++] = substr($item, 1, strlen($item)-2);
}
} else {
return false;
}
return $finalResult;
}
}