<?php
/*
* mysql表結構處理類
* 建立數據表,增長,編輯,刪除表中字段
*
*/
class MysqlManage{
/*
* 建立數據庫,而且主鍵是aid
* table 要查詢的表名
*/
function createTable($table){
$sql="CREATE TABLE IF NOT EXISTS `$table` (`aid` INT NOT NULL primary key)ENGINE = InnoDB;";
M()->execute($sql);
$this->checkTable($table);
}
/*
* 檢測表是否存在,也能夠獲取表中全部字段的信息
* table 要查詢的表名
* return 表裏全部字段的信息
*/
function checkTable($table){
$sql="desc `$table`";
$info=M()->execute($sql);
return $info;
}php
/*
* 檢測字段是否存在,也能夠獲取字段信息(只能是一個字段)
* table 表名
* field 字段名
*/
function checkField($table,$field){
$sql='desc `$table` $field';
$info=M()->execute($sql);
return $info;
}mysql
/*
* 添加字段
* table 表名
* info 字段信息數組 array
* return 字段信息 array
*/
function addField($table,$info){
$sql="alter table `$table` add column";
$sql.=$this->filterFieldInfo();
M()->execute($sql);
$this->checkField($table,$info['name']);
}sql
/*
* 修改字段
* 不能修改字段名稱,只能修改
*/
function editField($table,$info){
$sql="alter table `$table` modify ";
$sql.=$this->filterFieldInfo($info);
M()->execute($sql);
$this->checkField($table,$info['name']);
}數據庫
/*
* 字段信息數組處理,供添加更新字段時候使用
* info[name] 字段名稱
* info[type] 字段類型
* info[length] 字段長度
* info[isNull] 是否爲空
* info['default'] 字段默認值
* info['comment'] 字段備註
*/
private function filterFieldInfo($info){
if(!is_array($info))
return
$newInfo=array();
$newInfo['name']=$info['name'];
$newInfo['type']=$info['type'];
switch($info['type']){
case 'varchar':
case 'char':
$newInfo['length']=empty($info['length'])?100:$info['length'];
$newInfo['isNull']=$info['isNull']==1?'NULL':'NOT NULL';
$newInfo['default']=empty($info['default'])?'':'DEFAULT '.$info['default'];
$newInfo['comment']=empty($info['comment'])?'':'COMMENT '.$info['comment'];
break;
case 'int':
$newInfo['length']=empty($info['length'])?7:$info['length'];
$newInfo['isNull']=$info['isNull']==1?'NULL':'NOT NULL';
$newInfo['default']=empty($info['default'])?'':'DEFAULT '.$info['default'];
$newInfo['comment']=empty($info['comment'])?'':'COMMENT '.$info['comment'];
break;
case 'text':
$newInfo['length']='';
$newInfo['isNull']=$info['isNull']==1?'NULL':'NOT NULL';
$newInfo['default']='';
$newInfo['comment']=empty($info['comment'])?'':'COMMENT '.$info['comment'];
break;
}
$sql=$newInfo['name']." ".$newInfo['type'];
$sql.=(!empty($newInfo['length']))?($newInfo['length']) .' ':' ';
$sql.=$newInfo['isNull'].' ';
$sql.=$newInfo['default'];
$sql.=$newInfo['comment'];
return $sql;
}數組
/*
* 刪除字段
* 若是返回了字段信息則說明刪除失敗,返回false,則爲刪除成功
*/
function dropField($table,$field){
$sql="alter table `$table` drop column $field";
M()->execute($sql);
$this->checkField($table,$filed);
}this
/*
* 獲取指定表中指定字段的信息(多字段)
*/
function getFieldInfo($table,$field){
$info=array();
if(is_string($field)){
$this->checkField($table,$field);
}else{
foreach($field as $v){
$info[$v]=$this->checkField($table,$v);
}
}
return $info;
}
}get