PHP PDO_MYSQL 链式操作 非链式操作类

<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at the following url:           |
// | http://www.php.net/license/3_0.txt.                                  |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | [email protected] so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Original Author <[email protected]>                        |
// |          Your Name <[email protected]>                                 |
// +----------------------------------------------------------------------+
//
// $Id:$

class pdomysql {
    public  $dbtype = ‘mysql‘;
    public  $dbhost = ‘127.0.0.1‘;
    public  $dbport = ‘3306‘;
    public  $dbname = ‘test‘;
    public  $dbuser = ‘root‘;
    public  $dbpass = ‘‘;
    public  $charset = ‘utf-8‘;
    public  $stmt = null;
    public  $DB = null;
    public  $connect = true; // 是否長连接
    public  $debug = true;
    private  $parms = array();
    private $sql = array(
        "db" => "",
        "from" => "",
        "where" => "",
        "order" => "",
        "limit" => ""
    );
    /**
     * 构造函数
     */
    public function __construct() {

        $this->connect();
        $this->DB->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
        $this->DB->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
        $this->execute(‘SET NAMES ‘ . $this->charset);
    }
    /**
     * 析构函数
     */
    public function __destruct() {
        $this->close();
    }
    /**
     * *******************基本方法开始********************
     */
    /**
     * 作用:连結数据库
     */
    public function connect() {
        try {
            $this->DB = new PDO($this->dbtype . ‘:host=‘ . $this->dbhost . ‘;port=‘ . $this->dbport . ‘;dbname=‘ . $this->dbname, $this->dbuser, $this->dbpass, array(
                PDO::ATTR_PERSISTENT => $this->connect
            ));
        }
        catch(PDOException $e) {
            die("Connect Error Infomation:" . $e->getMessage());
        }
    }
    /**
     * 关闭数据连接
     */
    public function close() {
        $this->DB = null;
    }
    /**
     * 對字串進行转義
     */
    public function quote($str) {
        return $this->DB->quote($str);
    }
    /**
     * 作用:获取数据表里的欄位
     * 返回:表字段结构
     * 类型:数组
     */
    public function getFields($table) {
        $this->stmt = $this->DB->query("DESCRIBE $table");
        $result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
        $this->stmt = null;
        return $result;
    }
    /**
     * 作用:获得最后INSERT的主鍵ID
     * 返回:最后INSERT的主鍵ID
     * 类型:数字
     */
    public function getLastId() {
        return $this->DB->lastInsertId();
    }
    /**
     * 作用:執行INSERT\UPDATE\DELETE
     * 返回:执行語句影响行数
     * 类型:数字
     */
    public function execute($sql) {
        $this->getPDOError($sql);
        return $this->DB->exec($sql);
    }
    /**
     * 获取要操作的数据
     * 返回:合併后的SQL語句
     * 类型:字串
     */
    private function getCode($table, $args) {
        $code = ‘‘;
        if (is_array($args)) {
            foreach ($args as $k => $v) {
                if ($v == ‘‘) {
                    continue;
                }
                $code.= "`$k`=‘$v‘,";
            }
        }
        $code = substr($code, 0, -1);
        return $code;
    }
    public function optimizeTable($table) {
        $sql = "OPTIMIZE TABLE $table";
        $this->execute($sql);
    }
    /**
     * 执行具体SQL操作
     * 返回:运行結果
     * 类型:数组
     */
    private function _fetch($sql, $type) {
        $result = array();
        $this->stmt = $this->DB->query($sql);
        $this->getPDOError($sql);
        $this->stmt->setFetchMode(PDO::FETCH_ASSOC);
        switch ($type) {
            case ‘0‘:
                $result = $this->stmt->fetch();
                break;

            case ‘1‘:
                $result = $this->stmt->fetchAll();
                break;

            case ‘2‘:
                $result = $this->stmt->rowCount();
                break;
        }
        $this->stmt = null;
        return $result;
    }
    /**
     * *******************基本方法結束********************
     */
    /**
     * *******************Sql操作方法开始********************
     */
    /**
     * 作用:插入数据
     * 返回:表內記录
     * 类型:数组
     * 參数:$db->insert(‘$table‘,array(‘title‘=>‘Zxsv‘))
     */
    public function add($table, $args) {
        $sql = "INSERT INTO `$table` SET ";
        $code = $this->getCode($table, $args);
        $sql.= $code;
        return $this->execute($sql);
    }
    /**
     * 修改数据
     * 返回:記录数
     * 类型:数字
     * 參数:$db->up($table,array(‘title‘=>‘Zxsv‘),array(‘id‘=>‘1‘),$where
     * =‘id=3‘);
     */
    public function up($table, $args, $where) {
        $code = $this->getCode($table, $args);
        $sql = "UPDATE `$table` SET ";
        $sql.= $code;
        $sql.= " Where $where";
        return $this->execute($sql);
    }
    /**
     * 作用:刪除数据
     * 返回:表內記录
     * 类型:数组
     * 參数:$db->del($table,$condition = null,$where =‘id=3‘)
     */
    public function del($table, $where) {
        $sql = "DELETE FROM `$table` Where $where";
        return $this->execute($sql);
    }
    /**
     * 作用:获取單行数据
     * 返回:表內第一条記录
     * 类型:数组
     * 參数:$db->fetOne($table,$condition = null,$field = ‘*‘,$where =‘‘)
     */
    public function fetOne($table, $field = ‘*‘, $where = false) {
        $sql = "SELECT {$field} FROM `{$table}`";
        $sql.= ($where) ? " WHERE $where" : ‘‘;
        return $this->_fetch($sql, $type = ‘0‘);
    }
    /**
     * 作用:获取所有数据
     * 返回:表內記录
     * 类型:二維数组
     * 參数:$db->fetAll(‘$table‘,$condition = ‘‘,$field = ‘*‘,$orderby = ‘‘,$limit
     * = ‘‘,$where=‘‘)
     */
    public function fetAll($table, $field = ‘*‘, $orderby = false, $where = false) {
        $sql = "SELECT {$field} FROM `{$table}`";
        $sql.= ($where) ? " WHERE $where" : ‘‘;
        $sql.= ($orderby) ? " ORDER BY $orderby" : ‘‘;
        return $this->_fetch($sql, $type = ‘1‘);
    }
    /**
     * 作用:获取單行数据
     * 返回:表內第一条記录
     * 类型:数组
     * 參数:select * from table where id=‘1‘
     */
    public function getOne($sql) {
        return $this->_fetch($sql, $type = ‘0‘);
    }
    /**
     * 作用:获取所有数据
     * 返回:表內記录
     * 类型:二維数组
     * 參数:select * from table
     */
    public function getAll($sql) {
        return $this->_fetch($sql, $type = ‘1‘);
    }
    /**
     * 作用:获取首行首列数据
     * 返回:首行首列欄位值
     * 类型:值
     * 參数:select `a` from table where id=‘1‘
     */
    public function scalar($sql, $fieldname) {
        $row = $this->_fetch($sql, $type = ‘0‘);
        return $row[$fieldname];
    }
    /**
     * 获取記录总数
     * 返回:記录数
     * 类型:数字
     * 參数:$db->fetRow(‘$table‘,$condition = ‘‘,$where =‘‘);
     */
    public function fetRowCount($table, $field = ‘*‘, $where = false) {
        $sql = "SELECT COUNT({$field}) AS num FROM $table";
        $sql.= ($where) ? " WHERE $where" : ‘‘;
        return $this->_fetch($sql, $type = ‘0‘);
    }
    /**
     * 获取記录总数
     * 返回:記录数
     * 类型:数字
     * 參数:select count(*) from table
     */
    public function getRowCount($sql) {
        return $this->_fetch($sql, $type = ‘2‘);
    }
    //链式操作开始
    public function from($tableName) {
        $this->sql["from"] = "FROM " . $tableName;
        return $this;
    }
    public function db($tableName) {
        $this->sql["db"] = $tableName;
        return $this;
    }
    public function where($_where = ‘1=1‘) {
        $this->sql["where"] = "WHERE " . $_where;
        return $this;
    }
    public function order($_order = ‘id DESC‘) {
        $this->sql["order"] = "ORDER BY " . $_order;
        return $this;
    }
    public function limit($_limitstart="30",$_limitend = ‘0‘) {
        if ($_limitend=="0"){
            $this->sql["limit"] = "LIMIT 0," . $_limitstart;
        }else{
            $this->sql["limit"] = "LIMIT $_limitstart," . $_limitend;
        }

        return $this;
    }
    /**
     * 获取所有記录
     * 返回:所有記录
     * 类型:array
     * 參数: $pdomysql->from(‘dbname‘)->limit(30)->where(‘1=1‘)->select();
     */
    public function select($_select = ‘*‘) {
        //return "SELECT " . $_select . " " . (implode(" ", $this->sql));
        $sql="SELECT " . $_select . " " . (implode(" ", $this->sql));
        return $this->_fetch($sql, $type = ‘1‘);
    }
    /**
     * 获取一条記录
     * 返回:一条記录
     * 类型:array
     * 參数: $pdomysql->from(‘dbname‘)->limit(30)->where(‘1=1‘)->find();
     */
    public function find($_find = ‘*‘){
        $this->sql[‘limit‘]=‘limit 1‘;
        $sql="SELECT " . $_find . " " . (implode(" ", $this->sql));
        return $this->_fetch($sql, $type = ‘0‘);
    }
    /**
     * 插入一条数据
     * 返回:执行结果
     * 类型:bool
     * 參数: $pdomysql->db(‘dbname‘)->insert(array(‘col1‘="sadsd"));
     */
    public function insert($_insert=array()){
        $table=$this->sql[‘db‘];
        $sql = "INSERT INTO `$table` SET ";
        $code = $this->getCode($table, $args);
        $sql.= $code;
        return $this->execute($sql);
    }
    /**
     * 删除
     * 返回:删除结果
     * 类型:bool
     * 參数: $pdomysql->from(‘dbname‘)->where(‘1=1‘)->delete();
     */
    public function delete(){
        $sql="DELETE  " . (implode(" ", $this->sql));
        return $this->execute($sql);
    }
    public function update(){

    }
    //链式操作end
    /**
     * *******************Sql操作方法結束********************
     */
    /**
     * *******************错误处理开始********************
     */
    /**
     * 設置是否为调试模式
     */
    public function setDebugMode($mode = true) {
        return ($mode == true) ? $this->debug = true : $this->debug = false;
    }
    /**
     * 捕获PDO错误信息
     * 返回:出错信息
     * 类型:字串
     */
    private function getPDOError($sql) {
        $this->debug ? $this->errorfile($sql) : ‘‘;
        if ($this->DB->errorCode() != ‘00000‘) {
            $info = ($this->stmt) ? $this->stmt->errorInfo() : $this->DB->errorInfo();
            echo ($this->sqlError(‘mySQL Query Error‘, $info[2], $sql));
            exit();
        }
    }
    private function getSTMTError($sql) {
        $this->debug ? $this->errorfile($sql) : ‘‘;
        if ($this->stmt->errorCode() != ‘00000‘) {
            $info = ($this->stmt) ? $this->stmt->errorInfo() : $this->DB->errorInfo();
            echo ($this->sqlError(‘mySQL Query Error‘, $info[2], $sql));
            exit();
        }
    }
    /**
     * 寫入错误日志
     */
    private function errorfile($sql) {
        echo $sql . ‘<br />‘;
        $errorfile = __DIR__ . ‘/dberrorlog.php‘;
        $sql = str_replace(array(
            "\n",
            "\r",
            "\t",
            "  ",
            "  ",
            "  "
        ) , array(
            " ",
            " ",
            " ",
            " ",
            " ",
            " "
        ) , $sql);
        if (!file_exists($errorfile)) {
            $fp = file_put_contents($errorfile, "<?PHP exit(‘Access Denied‘); ?>\n" . $sql);
        } else {
            $fp = file_put_contents($errorfile, "\n" . $sql, FILE_APPEND);
        }
    }
    /**
     * 作用:运行错误信息
     * 返回:运行错误信息和SQL語句
     * 类型:字符
     */
    private function sqlError($message = ‘‘, $info = ‘‘, $sql = ‘‘) {
        $html = ‘‘;
        if ($message) {
            $html.= $message;
        }
        if ($info) {
            $html.= ‘SQLID: ‘ . $info;
        }
        if ($sql) {
            $html.= ‘ErrorSQL: ‘ . $sql;
        }
        throw new Exception($html);
    }
    /**
     * *******************错误处理結束********************
     */
}

原文地址:https://www.cnblogs.com/chbyl/p/10199146.html

时间: 2024-08-29 09:29:42

PHP PDO_MYSQL 链式操作 非链式操作类的相关文章

Java基础知识强化之多线程笔记07:同步、异步、阻塞式、非阻塞式 的联系与区别

1. 同步: 所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回.但是一旦调用返回,就必须先得到返回值了. 换句话话说,调用者主动等待这个"调用"的结果. 对于同步调用来说,很多时候当前线程还是激活的,只是从逻辑上当前函数没有返回而已. 2. 异步: 所谓异步,"调用"在发出之后,这个调用就直接返回了,所以没有返回结果. 换句话说,当一个异步过程调用发出后,调用者不会立刻得到结果.而是在"调用"发出后,"被调用者&q

Spring 侵入式和非侵入式

1.非侵入式的技术体现 允许在应用系统中自由选择和组装Spring框架的各个功能模块,并且不强制要求应用系统的类必须从Spring框架的系统API的某个类来继承或者实现某个接口. 2.如何实现非侵入式的设计目标的 1)应用反射机制,通过动态调用的方式来提供各方面的功能,建立核心组间BeanFactory 2)配合使用Spring框架中的BeanWrapper和BeanFactory组件类最终达到对象的实例创建和属性注入 3)优点:允许所开发出来的应用系统能够在不用的环境中自由移植,不需要修改应用

侵入式和非侵入式的区别

非侵入式设计 一个客户端的代码可能包含框架功能和客户端自己的功能. 侵入式设计,就是设计者将框架功能“推”给客户端,而非侵入式设计,则是设计者将客户端的功能“拿”到框架中用. 侵入式设计有时候表现为客户端需要继承框架中的类,而非侵入式设计则表现为客户端实现框架提供的接口. 侵入式设计带来的最大缺陷是,当你决定重构你的代码时,发现之前写过的代码只能扔掉.而非侵入式设计则不然,之前写过的代码仍有价值. struts1的设计是侵入式的: public class loginAction extends

登录式与非登录式&amp;交互式与非交互式shell及其环境初始化过程

交互式shell和非交互式shell(interactive shell and non-interactive shell) 交互式模式就是在终端上执行,shell等待你的输入,并且立即执行你提交的命令.这种模式被称作交互式是因为shell与用户进行交互.这种模式也是大多数用户非常熟悉的:登录.执行一些命令.退出.当你退出后,shell也终止了. shell也可以运行在另外一种模式:非交互式模式,以shell script(非交互)方式执行.在这种模式 下,shell不与你进行交互,而是读取存

Java基础:非阻塞式IO

转载请注明出处:jiq?钦's technical Blog 引言 JDK1.4中引入了NIO,即New IO,目的在于提高IO速度.特别注意JavaNIO不完全是非阻塞式IO(No-Blocking IO),因为其中部分通道(如FileChannel)只能运行在阻塞模式下,而其他的通道可以在阻塞式和非阻塞式之间进行选择. 尽管这样,我们还是习惯将Java NIO看作是非阻塞式IO,而前面介绍的面向流(字节/字符)的IO类库则是非阻塞的,详细来看,两者区别如下: IO NIO 面向流(Strea

前段时间用java做了个非阻塞式仿飞秋聊天程序

采用Swing 布局 NIO非阻塞式仿飞秋聊天程序, 切换皮肤颜色什么的小功能以后慢慢做 启动主程序. 当用户打开主程序后自动获取局域网段IP可以在 设置 --> IP网段过滤, 拥有 JMF 视频聊天功能(取得视频流读取到ByteBuffer然后写入DatagramChannel), 其实什么功能都是可以加的后期, 简单介绍下 双击用户进行聊天 (第一版是基于channel通道的操作, 非阻塞式, 这一版本为阻塞式) 当有消息发来时自动开启一个线程处理客户端请求并接受数据,并在标题上提示收到新

链队列——队列的链式表示和实现

一.单链队列的链式存储结构 相关代码下载链接:http://download.csdn.net/detail/shengshengwang/8141633 队列是操作受限的线性表,只允许在队尾插入元素,在队头删除元素.对于链队列结构,为了便于插入元素,设立了队尾指针,这样插入元素的操作便与队列长度无关.存储结构,如下所示: typedef int QElemType; typedef struct QNode { QElemType data; QNode *next; } *QueuePtr;

jQuery——链式编程与隐式迭代

链式编程 1.原理:return this; 2.通常情况下,只有设置操作才能把链式编程延续下去.因为获取操作的时候,会返回获取到的相应的值,无法返回 this. 3.end():结束当前链最近的一次过滤操作,并且返回匹配元素之前的状态. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title

数往知来 JQuery_选择器_隐式迭代_链式编程 &lt;二十&gt;

一.通过js实现页面加载完毕执行代码的方式与jquery的区别 1.通过jquery的方式可以 让多个方法被执行,而通过window.onload的方式只能执行最后一个, 因为最后一次注册的方法会把前面的方法覆盖掉 1. window.onload需要等待页面的所有元素资源比如说img里的图片一些连接等等都下载完毕后才会触发: 2. 而jquery只要页面的标签元素都下载完毕就会触发了 二.$.map(数组,function(ele,index){})函数对数组进行遍历,遍历之后会返回一个新的数