为mysql枚举选择的php函数 [英] php function for mysql enum selected

查看:116
本文介绍了为mysql枚举选择的php函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我创建了一个函数,该函数将从数据库中的枚举字段中提取值:

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;
}
?>

我正在以HTML形式执行此函数,将值拉出并在下拉列表中列出来就像一种魅力.这是我正在使用的:

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>

但是,我无法弄清楚如何使默认值(又名SELECTED)在下拉列表中显示为默认值.我现在所拥有的将重命名当前使用的值selected=<value1>,但是它没有将其设置为默认值.有人可以协助吗?我的问题有意义吗?

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?

谢谢!

现在,已经修复了语法错误,这是工作代码:

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>

推荐答案

要在select元素中选择一个或多个项目,只需将"selected"放在元素内,例如:

To select one ore more items in the select element you only have to put the "selected" inside the element like:

<select id="unittype" name="unittype">
  <option value="1"> Miner </option>
  <option value="2"> Puffer </option>
  <option value="3" selected> Snipey </option>
  <option value="4"> Max </option>
  <option value="5"> Firebot </option>
</select>

在此处选择了Snipey(值= 3).

here the Snipey (value=3) is selected.

所以在您的示例中,它必须位于...内,也许只是一个错字:

So in your example it have to be inside the ... maybe it was only a typo:

 <option <?php echo $selected; ?>><?php echo $option ?></option>

汤姆,oe1tkt

这篇关于为mysql枚举选择的php函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆