PHP :: Menampilkan data enum dari database ke dropdown select box

code ini ya sederhana tapi buat yang belum tau ya puyeng juga, hehe, kalau kalian udah kefikiran sampai cari tutorial ini.. selamat.. anda sudah sedikit berfikir maju, terus lah berjuang untuk membuat pekerjaan anda semakin cepat dan simple. oke ini codenya :

$table_name = "your_table_name"
$column_name = "field_with_enum_options";

echo "<select name=\"$column_name\">";
$result = mysql_query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = '$table_name' AND COLUMN_NAME = '$column_name'")
or die (mysql_error());

$row = mysql_fetch_array($result);
$enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));

foreach($enumList as $value)
    echo "<option value=\"$value\">$value</option>";

echo "</select>";


kalau mau pakai function dibawah ini :

function enumDropdown($table_name, $column_name, $echo = false)
{
   $selectDropdown = "<select name=\"$column_name\">";
   $result = mysql_query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
       WHERE TABLE_NAME = '$table_name' AND COLUMN_NAME = '$column_name'")
   or die (mysql_error());

    $row = mysql_fetch_array($result);
    $enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));

    foreach($enumList as $value)
         $selectDropdown .= "<option value=\"$value\">$value</option>";

    $selectDropdown .= "</select>";

    if ($echo)
        echo $selectDropdown;

    return $selectDropdown;
}
Please follow and like us:
10

Leave a Reply

Your email address will not be published. Required fields are marked *