简体   繁体   English

重命名php select元素的MYSQL列名

[英]Rename MYSQL column names for php select element

Hi I'm constructing a html select element like so: 嗨,我正在构造一个html select元素,如下所示:

$result = mysql_query("SHOW COLUMNS FROM table") or die(mysql_error());
    echo '<select name="column" class="column">';
    while ($row = mysql_fetch_array($result))
    {
        if($row[0] == 'id' || $row[0] == 'tstamp' || $row[0] == 'boiler2oil')
              continue;
        echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
    }
    echo '</select>';

The way i've named the columns in the table is rather ugly, with underscores, etc...how can i rename them so i can change the select element display (value can stay the same) changes to something a bit more readable and visually pleasing. 我在表中命名列的方式相当丑陋,带有下划线等。我该如何重命名它们,以便可以更改选择元素的显示(值可以保持不变)更改,使其更具可读性和视觉上令人愉悦。 Is this possible? 这可能吗? Would it be some sort of preg_match/preg_replace? 会是某种preg_match / preg_replace吗?

可能仅用str_replace就能完成,对于像这样的简单事情,它比preg_replace更有效。

Depends what you want to rename them to. 取决于您要将它们重命名为什么。 Do you want to do something simple like remove underscores? 您是否想做一些简单的事情,例如删除下划线? Is there a rule you can use to clean them all up? 有没有可以用来清理它们的规则?

If not, why not add a hash with entries that map from the name in the table to the name you want to print out for the drop-down list? 如果不是,为什么不添加带有从表中的名称映射到要为下拉列表打印的名称的条目的哈希呢?

# map from column name to display name
$labels = array(
    'col1' => 'Column 1',
    ...
);

$result = mysql_query("SHOW COLUMNS FROM table") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result))
{
    if($row[0] == 'id' || $row[0] == 'tstamp' || $row[0] == 'boiler2oil')
          continue;

    # use a more friendly name if one has been defined above in $labels
    if(array_key_exists($row[0], $labels))
          $label = $labels[$row[0]];
    else
          $label = $row[0];

    echo "<option value='".$row[0]."'>".$label."</option>";
}
echo '</select>';

You can define an array which will be having columnName as "key" and Name to Display as "value". 您可以定义一个将columnName作为“键”,将要显示的名称作为“ value”的数组。 Then Echo element of this array rather than displaying column name. 然后此数组的Echo元素而不是显示列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM