Db::getFields PHP Method

getFields() public method

取得数据表的字段信息
public getFields ( $tableName )
    public function getFields($tableName)
    {
        $result = $this->query('SHOW COLUMNS FROM ' . $tableName);
        $info = array();
        if ($result) {
            foreach ($result as $key => $val) {
                $info[$val['Field']] = array('name' => $val['Field'], 'type' => $val['Type'], 'notnull' => (bool) ($val['Null'] === ''), 'default' => $val['Default'], 'primary' => strtolower($val['Key']) == 'pri', 'autoinc' => strtolower($val['Extra']) == 'auto_increment');
            }
        }
        return $info;
    }

Usage Example

Example #1
0
 /**
  * 构造函数
  * @param string $name 模型名称
  * @param array|string $params 参数
  */
 public function __construct($name = '', $params = '')
 {
     // 有指定的模型
     if ($name) {
         $className = 'Model_' . ucfirst($name);
         // 用指定模型的属性值覆盖默认属性值
         if (class_exists($className)) {
             $this->instCoreiation($className);
         } else {
             if (defined('MO_PATH')) {
                 $filename = MO_PATH . substr($className, strrpos($className, '_') + 1) . '.php';
                 if (is_file($filename)) {
                     require_once $filename;
                 }
                 if (class_exists($className)) {
                     $this->instCoreiation($className);
                 }
             }
             $this->_tbl = $name;
         }
     }
     if (is_string($params)) {
         $this->tblPre = $params;
     } elseif (isset($params['tbl_pre'])) {
         $this->tblPre = $params['tbl_pre'];
     } elseif (is_null($this->tblPre)) {
         $this->tblPre = C('tbl_pre');
     }
     $this->tbl = $this->tblPre . $this->_tbl;
     // 载入字段配置
     $cfgName = 'fields/' . $this->_tbl;
     $this->fields = Core::C($cfgName);
     if (!$this->fields) {
         $this->fields = Db::getFields($this->tbl);
         // 设置主键信息
         if (is_array($this->fields)) {
             foreach ($this->fields as $field => $v) {
                 if ($v['Key'] == 'PRI') {
                     $this->fields['_PRI_'] = $field;
                     $this->priKey = $field;
                 }
             }
             Core::setC($cfgName, $this->fields);
         }
     } else {
         if (isset($this->fields['_PRI_'])) {
             $this->priKey = $this->fields['_PRI_'];
         }
     }
     /**
      * 实例模型类的表对应主键字段名
      */
     if ($this->instanceClass && $this->instanceClass->priKey == 'id') {
         $this->instanceClass->priKey = $this->priKey;
     }
 }