Semiauto Select/Option code

liderbug

New member
I have a web page generated from a sql db - calendar. I got tired of having to update the code for every any minor change with Enum columns in the db. So...


Code:
 <?php
  
  # Func: DB, Table, Column, prev.selected, prefix if joined tables
  # joined tables: tabA data for web display, 
  #  tabB data for admin, how paid, contact info, notifications

  function do_enum ($db, $table, $ecol, $seled, $ab)
  {
    # get the list of unums
    $q1 = mysqli_query ($db, "show columns from $table where field = '$ecol';");
    $u1 = mysqli_fetch_row ($q1);
    # convert to an array
    $enumarr = preg_split ("/\,/", (str_replace ("'", "", substr($u1[1], 5, -1))));
    # which one was selected?
    $sel=0;
    foreach ($enumarr as $l)
    { 
      if ("$l" == "$seled") break;
      $sel++;
    }
    # generate code
    $n=0;
    echo "<select name=$ab$ecol>\n";
    foreach ($enumarr as $item)
    {
      $seled = ($sel == $n) ? "selected":""; # which one gets "selectED"
      echo "<option value=$item $seled>$item\n";
      $n++;
    }
    echo "</select>";
  }

do_enum ($db, 'table', 'column', 'lastseled', 'b');


The function call is: $DB, tableName, columnName, item4selected, multitable.
The function queries the DB table and gets the Enums: item1, item2, ..itemN
and creates the <select name=column ... $sel($n) = (int)enum item to set "selected"
on the <option line. 'b' is (on my site "a" or "b" - joined tables IE aid = bid, aname, bnote[/code]
 
Last edited:
Please review the code below:

Code:
<?php
 
function do_enum ($db, $table, $ecol, $seled, $ab)
{
    // remove unwanted data from inputs
    $table = mysqli_real_escape_string($db, $table);
    $ecol = mysqli_real_escape_string($db, $ecol);
    $seled = mysqli_real_escape_string($db, $seled);
    $ab = mysqli_real_escape_string($db, $ab);


      $q1 = mysqli_query($db, "SHOW COLUMNS FROM $table WHERE Field = '$ecol';");


    if (!$q1) {       
        echo "Error in getting column information: " . mysqli_error($db);
        return;
    }


    $u1 = mysqli_fetch_row($q1);   
    $enumarr = preg_split("/\,/", str_replace("'", "", substr($u1[1], 5, -1)));   
    $sel = array_search($seled, $enumarr);   
    echo "<select name=\"$ab$ecol\">\n";
    
    foreach ($enumarr as $n => $item) {
        $selected = ($sel === $n) ? "selected" : "";
        echo "<option value=\"$item\" $selected>$item\n";
    }


    echo "</select>";
}
// Example
do_enum($db, 'your_table', 'your_column', 'last_selected', 'b');
?>

I hope it will work for you.
 
Back
Top