<?php
/**
* ! Medoo 0.8.5 - Copyright 2013, Angel Lai - MIT license - http://medoo.in
*/
class medoo{
protected $database_type = 'mysql'; // For MySQL, MSSQL, Sybase
protected $server = 'localhost'; protected $username = 'username'; protected $password = 'password'; // For SQLite
protected $database_file = ''; // Optional
protected $charset = 'utf8';
protected $database_name = '';
protected $option = array(); public function __construct($options){
try{
$type = strtolower($this -> database_type);
if(is_string($options)){
if($type == 'sqlite'){
$this -> database_file = $options;
}else{
$this -> database_name = $options;
}
}else{
foreach($options as $option => $value){
$this -> $option = $value;
}
}
$type = strtolower($this -> database_type);
switch($type){
case 'mysql':case 'pgsql':$this -> pdo = new PDO($type . ':host=' . $this -> server . ';dbname=' . $this -> database_name, $this -> username, $this -> password, $this -> option);
break;
case 'mssql':case 'sybase':$this -> pdo = new PDO($type . ':host=' . $this -> server . ';dbname=' . $this -> database_name . ',' . $this -> username . ',' . $this -> password, $this -> option);
break;
case 'sqlite':$this -> pdo = new PDO($type . ':' . $this -> database_file, $this -> option);
break;
}
$this -> pdo -> exec('SET NAMES \'' . $this -> charset . '\'');
}
catch(PDOException$e){
echo $e -> getMessage();
}
}
public function query($query){
$this -> queryString = $query;
return $this -> pdo -> query($query);
}
public function exec($query){
$this -> queryString = $query;
return $this -> pdo -> exec($query);
}
public function quote($string){
return $this -> pdo -> quote($string);
}
protected function array_quote($array){
$temp = array();
foreach($array as $value){
$temp[] = is_int($value)?$value:$this -> pdo -> quote($value);
}
return implode($temp, ',');
}
protected function inner_conjunct($data, $conjunctor, $outer_conjunctor){
$haystack = array();
foreach($data as $value){
$haystack[] = '(' . $this -> data_implode($value, $conjunctor) . ')';
}
return implode($outer_conjunctor . ' ', $haystack);
}
protected function data_implode($data, $conjunctor, $outer_conjunctor = null){
$wheres = array();
foreach($data as $key => $value){
if(($key == 'AND' || $key == 'OR') && is_array($value)){
$wheres[] = 0 !== count(array_diff_key($value, array_keys(array_keys($value))))?'(' . $this -> data_implode($value, ' ' . $key) . ')':'(' . $this -> inner_conjunct($value, ' ' . $key, $conjunctor) . ')';
}else{
preg_match('/([\w\.]+)(\[(\>|\>\=|\<|\<\=|\!|\<\>)\])?/i', $key, $match);
if(isset($match[3])){
if($match[3] == '' || $match[3] == '!'){
$wheres[] = $match[1] . ' ' . $match[3] . '= ' . $this -> quote($value);
}else{
if($match[3] == '<>'){
if(is_array($value)){
if(is_numeric($value[0]) && is_numeric($value[1])){
$wheres[] = $match[1] . ' BETWEEN ' . $value[0] . ' AND ' . $value[1];
}else{
$wheres[] = $match[1] . ' BETWEEN ' . $this -> quote($value[0]) . ' AND ' . $this -> quote($value[1]);
}
}
}else{
if(is_numeric($value)){
$wheres[] = $match[1] . ' ' . $match[3] . ' ' . $value;
}
}
}
}else{
if(is_int($key)){
$wheres[] = $this -> quote($value);
}else{
switch(gettype($value)){
case 'NULL':$wheres[] = $match[1] . ' IS null';
break;
case 'array':$wheres[] = $match[1] . ' IN (' . $this -> array_quote($value) . ')';
break;
default:$wheres[] = $match[1] . ' = ' . $this -> quote($value);
break;
}
}
}
}
}
return implode($conjunctor . ' ', $wheres);
}
public function where_clause($where){
$where_clause = '';
if(is_array($where)){
$single_condition = array_diff_key($where, array_flip(explode(' ', 'AND OR GROUP ORDER HAVING LIMIT LIKE MATCH')));
if($single_condition != array()){
$where_clause = ' WHERE ' . $this -> data_implode($single_condition, '');
}
if(isset($where['AND'])){
$where_clause = ' WHERE ' . $this -> data_implode($where['AND'], ' AND ');
}
if(isset($where['OR'])){
$where_clause = ' WHERE ' . $this -> data_implode($where['OR'], ' OR ');
}
if(isset($where['LIKE'])){
$like_query = $where['LIKE'];
if(is_array($like_query)){
$is_OR = isset($like_query['OR']);
if($is_OR || isset($like_query['AND'])){
$connector = $is_OR?'OR':'AND';
$like_query = $is_OR?$like_query['OR']:$like_query['AND'];
}else{
$connector = 'AND';
}
$clause_wrap = array();
foreach($like_query as $column => $keyword){
if(is_array($keyword)){
foreach($keyword as $key){
$clause_wrap[] = $column . ' LIKE ' . $this -> quote('%' . $key . '%');
}
}else{
$clause_wrap[] = $column . ' LIKE ' . $this -> quote('%' . $keyword . '%');
}
}
$where_clause .= ($where_clause != ''?' AND ':' WHERE ') . '(' . implode($clause_wrap, ' ' . $connector . ' ') . ')';
}
}
if(isset($where['MATCH'])){
$match_query = $where['MATCH'];
if(is_array($match_query) && isset($match_query['columns']) && isset($match_query['keyword'])){
$where_clause .= ($where_clause != ''?' AND ':' WHERE ') . ' MATCH (' . implode($match_query['columns'], ', ') . ') AGAINST (' . $this -> quote($match_query['keyword']) . ')';
}
}
if(isset($where['GROUP'])){
$where_clause .= ' GROUP BY ' . $where['GROUP'];
}
if(isset($where['ORDER'])){
$where_clause .= ' ORDER BY ' . $where['ORDER'];
if(isset($where['HAVING'])){
$where_clause .= ' HAVING ' . $this -> data_implode($where['HAVING'], '');
}
}
if(isset($where['LIMIT'])){
if(is_numeric($where['LIMIT'])){
$where_clause .= ' LIMIT ' . $where['LIMIT'];
}
if(is_array($where['LIMIT']) && is_numeric($where['LIMIT'][0]) && is_numeric($where['LIMIT'][1])){
$where_clause .= ' LIMIT ' . $where['LIMIT'][0] . ',' . $where['LIMIT'][1];
}
}
}else{
if($where != null){
$where_clause .= ' ' . $where;
}
}
return $where_clause;
}
public function select($table, $columns, $where = null){
$where_clause = $this -> where_clause($where);
preg_match('/([a-zA-Z0-9_-]*)\s*(\[(\<|\>|\>\<|\<\>)\])?\s*([a-zA-Z0-9_-]*)/i', $table, $match);
if($match[3] != '' && $match[4] != ''){
$join_array = array('>' => 'LEFT', '<' => 'RIGHT', '<>' => 'FULL', '><' => 'INNER');
$table = $match[1] . ' ' . $join_array[$match[3]] . ' JOIN ' . $match[4] . ' ON ';
$where_clause = str_replace(' WHERE ', '', $where_clause);
}
$query = $this -> query('SELECT ' . (is_array($columns)?implode(', ', $columns):$columns) . ' FROM ' . $table . $where_clause);
return $query?$query -> fetchAll((is_string($columns) && $columns != '*')?PDO :: FETCH_COLUMN:PDO :: FETCH_ASSOC):false;
}
public function insert($table, $data){
$keys = implode(',', array_keys($data));
$values = array();
foreach($data as $key => $value){
$values[] = is_array($value)?serialize($value):$value;
}
$this -> exec('INSERT INTO ' . $table . ' (' . $keys . ') VALUES (' . $this -> data_implode(array_values($values), ',') . ')');
return $this -> pdo -> lastInsertId();
}
public function update($table, $data, $where = null){
$fields = array();
foreach($data as $key => $value){
if(is_array($value)){
$fields[] = $key . '=' . $this -> quote(serialize($value));
}else{
preg_match('/([\w]+)(\[(\+|\-)\])?/i', $key, $match);
if(isset($match[3])){
if(is_numeric($value)){
$fields[] = $match[1] . ' = ' . $match[1] . ' ' . $match[3] . ' ' . $value;
}
}else{
$fields[] = $key . ' = ' . $this -> quote($value);
}
}
}
return $this -> exec('UPDATE ' . $table . ' SET ' . implode(',', $fields) . $this -> where_clause($where));
}
public function delete($table, $where){
return $this -> exec('DELETE FROM ' . $table . $this -> where_clause($where));
}
public function replace($table, $columns, $search = null, $replace = null, $where = null){
if(is_array($columns)){
$replace_query = array();
foreach($columns as $column => $replacements){
foreach($replacements as $replace_search => $replace_replacement){
$replace_query[] = $column . ' = REPLACE(' . $column . ', ' . $this -> quote($replace_search) . ', ' . $this -> quote($replace_replacement) . ')';
}
}
$replace_query = implode(', ', $replace_query);
$where = $search;
}else{
if(is_array($search)){
$replace_query = array();
foreach($search as $replace_search => $replace_replacement){
$replace_query[] = $columns . ' = REPLACE(' . $columns . ', ' . $this -> quote($replace_search) . ', ' . $this -> quote($replace_replacement) . ')';
}
$replace_query = implode(', ', $replace_query);
$where = $replace;
}else{
$replace_query = $columns . ' = REPLACE(' . $columns . ', ' . $this -> quote($search) . ', ' . $this -> quote($replace) . ')';
}
}
return $this -> exec('UPDATE ' . $table . ' SET ' . $replace_query . $this -> where_clause($where));
}
public function get($table, $columns, $where = null){
if(is_array($where)){
$where['LIMIT'] = 1;
}
$data = $this -> select($table, $columns, $where);
return isset($data[0])?$data[0]:false;
}
public function has($table, $where){
return $this -> query('SELECT EXISTS(SELECT 1 FROM ' . $table . $this -> where_clause($where) . ')') -> fetchColumn() === '1';
}
public function count($table, $where = null){
return 0 + ($this -> query('SELECT COUNT(*) FROM ' . $table . $this -> where_clause($where)) -> fetchColumn());
}
public function max($table, $column, $where = null){
return 0 + ($this -> query('SELECT MAX(' . $column . ') FROM ' . $table . $this -> where_clause($where)) -> fetchColumn());
}
public function min($table, $column, $where = null){
return 0 + ($this -> query('SELECT MIN(' . $column . ') FROM ' . $table . $this -> where_clause($where)) -> fetchColumn());
}
public function avg($table, $column, $where = null){
return 0 + ($this -> query('SELECT AVG(' . $column . ') FROM ' . $table . $this -> where_clause($where)) -> fetchColumn());
}
public function sum($table, $column, $where = null){
return 0 + ($this -> query('SELECT SUM(' . $column . ') FROM ' . $table . $this -> where_clause($where)) -> fetchColumn());
}
public function error(){
return $this -> pdo -> errorInfo();
}
public function last_query(){
return $this -> queryString;
}
public function info(){
return array('server' => $this -> pdo -> getAttribute(PDO :: ATTR_SERVER_INFO), 'client' => $this -> pdo -> getAttribute(PDO :: ATTR_CLIENT_VERSION), 'driver' => $this -> pdo -> getAttribute(PDO :: ATTR_DRIVER_NAME), 'version' => $this -> pdo -> getAttribute(PDO :: ATTR_SERVER_VERSION), 'connection' => $this -> pdo -> getAttribute(PDO :: ATTR_CONNECTION_STATUS));
}
}
?>

超轻量级PHP SQL数据库框架的更多相关文章

  1. Android数据库框架——GreenDao轻量级的对象关系映射框架,永久告别sqlite

    Android数据库框架--GreenDao轻量级的对象关系映射框架,永久告别sqlite 前不久,我在写了ORMLite这个框架的博文 Android数据库框架--ORMLite轻量级的对象关系映射 ...

  2. Android数据库框架——ORMLite轻量级的对象关系映射(ORM)Java包

    Android数据库框架--ORMLite轻量级的对象关系映射(ORM)Java包 事实上,我想写数据库的念头已经很久了,在之前写了一个答题系统的小项目那只是初步的带了一下数据库,数据库是比较强大的, ...

  3. 腾讯正式开源高性能超轻量级 PHP 框架 Biny

    概况 Biny是一款高性能的超轻量级PHP框架 遵循 MVC 模式,用于快速开发现代 Web 应用程序 Biny代码简洁优雅,对应用层,数据层,模板渲染层的封装简单易懂,能够快速上手使用 高性能,框架 ...

  4. 推荐一款轻量级PHP数据库框架–Medoo

    引用官网的简介: 可以加快开发速度的最轻量级的PHP数据库框架 为什么选择Medoo及其主要功能: 轻量级–单个文件,只有20KB 易用–非常容易学习和使用 功能强大–支持各种常见和复杂的SQL查询 ...

  5. ORM数据库框架 greenDAO SQLite MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. iOS---SQLite数据库框架之FMDB -Swift

    SQLite数据库框架之FMDB 什么是FMDB? FMDB是iOS平台的SQLite数据库框架,FMDB以OC的方式封装了SQLite的C语言API.对比苹果自带的Core Data框架,更加轻量级 ...

  7. Android 数据库框架ormlite

    Android 数据库框架ormlite 使用精要 前言 本篇博客记录一下笔者在实际开发中使用到的一个数据库框架,这个可以让我们快速实现数据库操作,避免频繁手写sql,提高我们的开发效率,减少出错的机 ...

  8. ORM数据库框架 SQLite 常用数据库框架比较 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  9. SQLite数据库框架--FMDB简单介绍

    1.什么是FMDB FMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API 2.FMDB的优点 使用起来更加面向对象,省去了很多麻烦.冗余的C语言代码 对比 ...

随机推荐

  1. 框架计划随笔 三.EntityFramework在传统事务脚本模式下的使用

    某个朋友问为什么不推首页或者允许评论,我说一直没怎么写博客,也习惯了先随便乱画再开始写文档,担心公开后一些不经意的"呓语“中得出的错误的结论会给别人错误的观点,所以这个系列只是当做熟悉写博客 ...

  2. Git--廖雪峰的博客的学习笔记

    为了督促自己能看完这个网站的学习教程,边看边做了些简要的笔记,记录了常用命令,其实也就是自己打了些简单的命令,好多直接就粘贴过来了,也算是一个学习的证明吧,想按详细的教程,还是要去博主的园子学习啊地址 ...

  3. hdu3507

    题意: 给n(n<=10^6)个非负数字,放在一个数组num中,再给一个特殊值m.求将这个数组分成任意多个区间,每个区间[a,b]的值定义为( sigma(num[i] | (a<=i&l ...

  4. [C#参考]锁定lock

    Lock关键字解释: lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁. 下面的示例包含一个 lock 语句. lock 关键字可确保当一个线程位于代码的临界区 ...

  5. linux grep 指定字符串的正则表达式

    cat all_uuid_log | grep "[a-z0-9]\{32\}"

  6. VC++学习之VC中常见问题

    VC++学习之VC中常见问题 (1)为什么某个类突然在工作区间里面突然看不见了? 只是类隐藏了,打开FILEVIEW,找到隐藏类的头文件,随便敲一下键盘的空格键,类就会在CLASSVIEW中显示了 ( ...

  7. python 关于dict的一些总结

    总结了一些关于字典的小技巧或者注意的地方. 使用zip创建字典 创建字典有以下三种方法 dict(a=1, b=2, c=2) dict([(a,1), (b,2), (c,3)]) dict({a: ...

  8. IOS 特定于设备的开发:监测Retina支持

    近年来,Apple在其旗舰设备上引入了Retina显示屏.根据Apple的说法,他的像素密度非常高,足以使人眼无法区分单独的像素. UIScreen类提供了一种容易的方式,用于监查当前设备是否提供了内 ...

  9. Apache服务无法启动的解决方法

    apache服务无法启动的解决方法 在配置apache的时候,把apache安装为服务myweb,用apacheMonitor启动myweb发现无法启动,提示:the requested operat ...

  10. 领域驱动设计系列(2)浅析VO、DTO、DO、PO的概念、区别和用处

    PO:persistant object持久对象 最形象的理解就是一个PO就是数据库中的一条记录.好处是可以把一条记录作为一个对象处理,可以方便的转为其它对象. BO:business object业 ...