<?php
include 'config.php';
class Model{
//用户名
protected $user;
//密码
protected $pwd;
//主机
protected $host;
//库名,是一个数组
protected $dbName=array();
//字符集
protected $charset='utf8';
//连接资源是一个数组
protected $_link=array();
//通用表名
protected $tabName;
//真实表名
protected $trueTabName;
//表前缀
protected $prefix;
//字段缓存
protected $fields;
//创建表的sql语句
protected $createSql='CREATE TABLE IF NOT EXISTS __TABLENAME__(
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`username` char(15) NOT NULL,
`password` char(32) NOT NULL,
`createtime` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;'; //1,通过ID取余,得到真实表名 mod
//2,用户名截取前几位 substr
//3,md5 md5
//4,不带分库分表 none protected $partition=array(
'type'=>'md5', 'rule'=>1, ); public function __construct($tabName=''){
$this->user=DB_USER;
$this->host=DB_HOST;
$this->dbName[0]=DB_NAME;
$this->charset=DB_CHARSET;
$this->prefix=DB_PREFIX;
$this->pwd=DB_PWD; if(empty($tabName)){
//userModel
//newModel
$this->tabName=$this->prefix.ucfirst(strtolower(substr(get_class($this),0,-5))); }else{
$this->tabName=$this->prefix.$tabName;
} $this->_link[0]=$this->connect($this->host,$this->user,$this->pwd,$this->dbName,$this->charset); } public function connect($host,$user,$pwd,$dbName,$charset,$linkId=0){
$conn=mysql_connect($host,$user,$pwd); if(mysql_errno()){
$this->error(-1,$conn);
return false;
} if(!$this->selectDb($dbName[$linkId],$conn)){
$this->error(-2,$conn);
return false;
} if(!$this->setCharset($charset,$conn)){
$this->error(-3,$conn);
return false;
} return $conn; } public function selectDb($dbName,$conn){
if(mysql_select_db($dbName,$conn)){ return true;
}else{
return false;
}
} public function setCharset($charset,$conn){
if(mysql_set_charset($charset,$conn)){
return true;
}else{
return false;
} } public function addServer($host,$user,$pwd,$dbName,$charset,$linkId){
$this->dbName[$linkId]=$dbName;
$this->_link[$linkId]=$this->connect($host,$user,$pwd,$dbName,$charset,$linkId); } public function getTrueTable($content,$linkId=0){
switch($this->partition['type']){
case 'mod':
if(!is_int($content)){
$this->error(-4);
return false;
}
$string=$content%$this->partition['rule'];
break;
case 'substr':
$string=substr($content,0,$this->partition['rule']);
break;
case 'md5':
$string=substr(md5($content),0,$this->partition['rule']);
break;
case 'none':
$string=null;
break;
} if(empty($string)){
$this->trueTableName=$this->tabName; }else{
$this->trueTableName=$this->tabName.'_'.$string;
} //第一,判断表是否存在,存在返回表字段缓存
//第二,不存在,则创建表,返回字段缓存 $this->existsTable($this->trueTableName,$linkId); }
//表是否存在
//是否缓存了字段 protected function existsTable($tableName,$linkId=0){
$database=$this->dbName[$linkId];
$sql='select `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`=\''.$database.'\' and `TABLE_NAME`=\''.$tableName.'\''; if($this->execute($sql,$linkId)){
//表存在
if(file_exists('cache/'.md5($this->tabName).'.php')){
$this->fields=include 'cache/'.md5($this->tabName).'.php';
}else{
//暂时留着不写,待会来写
$this->fields=$this->getFieldCache($linkId);
} }else{
//表不存在
$this->createTable($this->trueTableName,$linkId);
$this->fields=$this->getFieldCache($linkId); } } protected function getFieldCache($linkId=0){
if(file_exists('cache/'.md5($this->tabName).'.php')){
$fields=include 'cache/'.md5($this->tabName).'.php';
return $fields;
}
$sql="desc $this->trueTableName";
$f=$this->query($sql,$linkId); $fields=$this->writeFields($f); return $fields; } protected function writeFields($f){
foreach($f as $key=>$value){
$fields[]=$value['Field']; if($value['Key']=='PRI'){
$fields['_pk']=$value['Field'];
}
if($value['Extra']=='auto_increment'){
$fields['_auto']=$value['Field'];
}
}
$string="<?php \n return ".var_export($fields,true)."\n?>"; file_put_contents('cache/'.md5($this->tabName).'.php',$string);
return $fields; } protected function createTable($tabName,$linkId=0){
$sql=str_replace('__TABLENAME__',$tabName,$this->createSql); $this->execute($sql,$linkId);
} //不需要返回结果集我用execute方法
public function execute($sql,$linkId=0){
$conn=$this->_link[$linkId]; $result=mysql_query($sql,$this->_link[$linkId]);
if($result&&mysql_affected_rows()){ return mysql_affected_rows();
}else{
return false;
} } //需要返回结果集我用query方法
public function query($sql,$linkId=0){
$result=mysql_query($sql,$this->_link[$linkId]); if($result&&mysql_affected_rows()){
while($row=mysql_fetch_assoc($result)){ $rows[]=$row;
}
}else{
return false;
}
return $rows;
} public function error($num,$conn){
switch($num){
case -1:
$string='连接数据库服务器失败'.mysql_error($conn);
break;
case -2:
$string='选择数据失败';
break;
case -3:
$string='设置字符集失败';
break;
case -4:
$string='数据库路由时选择的是取余,传入的不是整型';
break;
}
} //查最大值
public function max($field,$linkId=0){
if(!in_array($field,$this->fields)){
return false;
}
$sql="select max($field) as re from $this->trueTableName";
$result=$this->query($sql,$linkId);
$row=$result['re'];
return $row; } //查最小值
public function min($field,$linkId=0){
if(!in_array($field,$this->fields)){
return false;
}
$sql="select min($field) as re from $this->trueTableName";
$result=$this->query($sql,$linkId);
$row=$result['re'];
return $row; }
//求和
public function sum($field,$linkId=0){
if(!in_array($field,$this->fields)){
return false;
}
$sql="select sum($field) as re from $this->trueTableName";
$result=$this->query($sql,$linkId);
$row=$result['re'];
return $row; }
//最平均数
public function avg($field,$linkId=0){
if(!in_array($field,$this->fields)){
return false;
}
$sql="select avg($field) as re from $this->trueTableName";
$result=$this->query($sql,$linkId);
$row=$result['re'];
return $row; }
//求总数
public function count($field='',$linkId=0){
if(empty($field)){
$field=$this->fields['_pk'];
}
$sql="select count($field) as re from $this->trueTableName";
$result=$this->query($sql,$linkId);
$row=$result['re'];
return $row;
}
//
//删除
public function delete($data,$where='',$linkId=0,$order='',$limit=''){
//delete from 表 where 字段 order by 字段 limit if(is_array($data)){
$value=join(',',$data);
}else{
$value=(int)$data;
}
$fields=$this->fields['_pk']; if(empty($where)){ $sql="delete from $this->trueTableName where $fields in ($value)";
}else{
$where='where '.$where;
if(!empty($order)){
$order='order by '.$order;
}
if(!empty($limit)){
$limit='limit '.$limit;
} $sql="delete from $this->trueTableName $where $order $limit";
}
return $this->execute($sql,$linkId);
}
//
//修改
public function save($data,$where,$linkId=0,$order='',$limit=''){ //update 表 set 字段=值,字段=值 where 条件 order limit
$key=array_keys($data);
$newKey=array_intersect($key,$this->fields); foreach($data as $key=>$value){
if(!in_array($key,$newKey))
continue;
$update.=$key.'="'.$value.'",'; }
$update=rtrim($update,','); if(!empty($order)){
$order='order by '.$order;
}
if(!empty($limit)){
$limit='limit '.$limit;
} if(!empty($where)){
$where='where '.$where;
} $sql="update $this->trueTableName set $update $where $order $limit"; echo $sql;
$result=$this->execute($sql,$linkId);
return $result; } //增加
public function add($data,$linkId=0){
//insert into 表(字段) values(值)
$key=array_keys($data);
$newKey=array_intersect($key,$this->fields);
foreach($data as $key=>$value){
if(!in_array($key,$newKey))
continue;
$values.="'".$value."',";
}
$values=trim($values,',');
$fields=join(',',$newKey);
$sql="insert into $this->trueTableName($fields) values($values)";
echo $sql;
$result=$this->execute($sql,$linkId);
return $result;
} //单条查询
public function find($linkId=0,$where='',$order=''){
//select * from 表 where order limit 1
$field=join(',',$this->fields);
if(!empty($where)){
$where='where '.$where;
}
if(!empty($order)){
$order='order by '.$order;
}
$sql="select $field from $this->trueTableName $where $order limit 1";
$result=$this->query($sql,$linkId);
return $result[0]; } //多条查询
public function select($field='',$linkId=0,$where='',$order='',$limit=''){
//select * from 表 where order limit
if(empty($field)){
$fields=join(',',$this->fields);
}else{
if(is_array($field)){
$newKey=array_intersect($field,$this->fields);
$fields=implode(',',$newKey);
}else{
$fields=$field;
}
}
if(!empty($where)){
$where='where '.$where;
}
if(!empty($order)){
$order='order by '.$order;
}
if(!empty($limit)){
$limit='limit '.$limit;
}
$sql="select $fields from $this->trueTableName $where $order $limit";
$result=$this->query($sql,$linkId);
return $result; }
//按照字段来查询数据 function __call($name,$param){
$key=substr($name,0,5);
if(strtolower($key)=='getby'){
$field=strtolower(substr($name,5)); if(!in_array($field,$this->fields)){
return false;
}
$f=join(',',$this->fields);
$value=$param[0];
$sql="select $f from $this->trueTableName where $field='$value'"; $result=$this->query($sql);
return $result[0]; }
} } ?>

php的分表分库类的更多相关文章

  1. .Net下的分库分表帮助类——用分库的思想来分表

    简介     在大型项目中,我们会遇到分表分库的情景.      分库,将不同模块对应的表拆分到对应的数据库下,其实伴随着公司内分布式系统的出现,这个过程也是自然而然就发生了,对应商品模块和用户模块, ...

  2. .NETCore 下支持分表分库、读写分离的通用 Repository

    首先声明这篇文章不是标题党,我说的这个类库是 FreeSql.Repository,它作为扩展库现实了通用仓储层功能,接口规范参考 abp vnext 定义,实现了基础的仓储层(CURD). 安装 d ...

  3. [NewLife.XCode]分表分库(百亿级大数据存储)

    NewLife.XCode是一个有15年历史的开源数据中间件,支持netcore/net45/net40,由新生命团队(2002~2019)开发完成并维护至今,以下简称XCode. 整个系列教程会大量 ...

  4. 分表分库解决方案(mycat,tidb,shardingjdbc)

    公司最近有分表分库的需求,所以整理一下分表分库的解决方案以及相关问题. 1.sharding-jdbc(sharding-sphere) 优点: 1.可适用于任何基于java的ORM框架,如:JPA. ...

  5. .NET ORM 分表分库【到底】怎么做?

    理论知识 分表 - 从表面意思上看呢,就是把一张表分成N多个小表,每一个小表都是完正的一张表.分表后数据都是存放在分表里,总表只是一个外壳,存取数据发生在一个一个的分表里面.分表后单表的并发能力提高了 ...

  6. Abp VNext分表分库,拒绝手动,我们要happy coding

    Abp VNext 分表分库 ShardingCore ShardingCore 易用.简单.高性能.普适性,是一款扩展针对efcore生态下的分表分库的扩展解决方案,支持efcore2+的所有版本, ...

  7. .Net分表分库动态化处理

    介绍 本期主角:ShardingCore 一款ef-core下高性能.轻量级针对分表分库读写分离的解决方案,具有零依赖.零学习成本.零业务代码入侵 背景 最近有个小伙伴来问我,分表下他有一批数据,这个 ...

  8. NetCore框架WTM的分表分库实现

    介绍 本期主角: ShardingCore 一款ef-core下高性能.轻量级针对分表分库读写分离的解决方案,具有零依赖.零学习成本.零业务代码入侵 WTM WalkingTec.Mvvm框架(简称W ...

  9. 学会数据库读写分离、分表分库——用Mycat,这一篇就够了!

    系统开发中,数据库是非常重要的一个点.除了程序的本身的优化,如:SQL语句优化.代码优化,数据库的处理本身优化也是非常重要的.主从.热备.分表分库等都是系统发展迟早会遇到的技术问题问题.Mycat是一 ...

随机推荐

  1. storm入门教程 第四章 消息的可靠处理【转】

    4.1 简介 storm可以确保spout发送出来的每个消息都会被完整的处理.本章将会描述storm体系是如何达到这个目标的,并将会详述开发者应该如何使用storm的这些机制来实现数据的可靠处理. 4 ...

  2. Android 的实现TextView中文字链接的4种方法

    Android 的实现TextView中文字链接的方式有很多种. 总结起来大概有4种: 1.当文字中出现URL.E-mail.电话号码等的时候,可以将TextView的android:autoLink ...

  3. SQL删除数据库里所有表的外键,同时删除所有用户表

    SQL删除数据库里所有表的外键,同时删除所有用户表 删除所有的用户表的外键,直接将下面的代码拷贝到数据库里执行即可: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  4. 国内外开源与 SaaS ,团队协作平台、项目管理工具整理

    整理一些开源与 SaaS ,团队协作平台.项目管理工具.还有哪些比较好的工具,可以推荐下? 名称 地址 备注 asana https://asana.com/ 国外 basecamp https:// ...

  5. MYSQL里的索引类型介绍

    首先要明白索引(index)是在存储引擎(storage engine)层面实现的,而不是在server层面.不是所有的存储引擎支持有的索引类型. 1.B-TREE 最常见的索引类型,他的思想是所有的 ...

  6. 二分+最短路 uvalive 3270 Simplified GSM Network(推荐)

    // 二分+最短路 uvalive 3270 Simplified GSM Network(推荐) // 题意:已知B(1≤B≤50)个信号站和C(1≤C≤50)座城市的坐标,坐标的绝对值不大于100 ...

  7. Oauth2 接口api

    weibo:http://open.weibo.com/wiki/API weixin:http://mp.weixin.qq.com/wiki/home/index.html   qq开发平台: 1 ...

  8. Deep Learning Practice【开篇】

    Chapter 0 初入深度学习实战 最近一直在学习深度学习相关的知识,看文献,看博客,看书,与别人讨论,等等,但是总觉得这样的学习只是停留在表面,无法去深入的学习到深度学习的内幕.于是,决定开始深度 ...

  9. MEAN stack 做网站【1】

    做一个小project,学习如何用MEAN技术栈来搭建网站. JavaScript新手,不足之处,请指出.(系统为win10) 搭建环境: 安装Node.JS (略过) 安装MySQL,MongoDB ...

  10. workstack windows to openstack

    https://www.mirantis.com/openstack-portal/express-openstack-portal/migrating-from-vmware-for-windows ...