Home php教程 php手册 用PHP开始你的MVC (二)抽象数据库接口

用PHP开始你的MVC (二)抽象数据库接口

Jun 21, 2016 am 09:07 AM
data gt mysql nbsp this

数据|数据库

二、抽象数据库接口(利用数据操作管理类)

在用mvc模式开发的时候,model层负责数据库的所有操作,为了对数据库的操作进行统一的管理,我们需要定义一个数据库操作管理类,由他来接替所有的数据库操作,也就是整个系统中只有这个数据库操作管理类,可以直接对数据库进行操作,如果其他的类需要对数据库进行操作,那它就必须调用和通过这个类来实现。

下面的Db类就是一个这样的类。

/**************************************************************
 *        descript : mysql数据库操作管理类
 *
 *          author : 大龄青年
 *           Email :wenadmin@sina.com
 *                 qq : 303015292
 *             msn : wenguangqing@hotmail.com
 *************************************************************/
/*
 * example 1:  获取序列
 *   
 *    $db = new Db();
 *    $result = $db->getSeq('art_id', 2, 1);
 *    ?>
 */
/*
 * example 2:  分页查询
 *   
 *    $db = new Db();
 *    $result = $db->&queryPage('select id,name from table', 2, 10, DB_FETCH_ASSOC);
 *    foreach($result as $row)
 *     echo $row['id'],'------'.$row['name'].'
';
 *    ?>
 */
/*
 * example 3:  插入数据
 *   
 *    $db = new Db();
 *    $result = $db->execute("insert into table (id, name) values(1,'name')");
 *    if($result>0)     echo '插入数据成功';
 *    else                   echo '插入数据失败';
 *    ?>
 */
/*
 * 定义数据库联接选项
 * @var  DB_HOST       string   数据库主机名称或地址
 * @var  DB_NAME       string   数据库名称
 * @var  DB_USER       string   数据库用户名称
 * @var  DB_PWD        string   数据库用户的密码
 * @var  DB_PCONNECT   boolean  是否建立持久连接
 */
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PWD', '');
define('DB_PCONNECT', true);
/*
 *定义返回数据查询结果的类型
 * @var  DB_FETCH_ASSOC   int  结果调用方式:$result['name']
 * @var  DB_FETCH_NUM     int  结果调用方式:$result[0]
 * @var  DB_FETCH_BOTH    int  结果调用方式:$result['name'] 或 $result[0]
 * @var  DB_FETCH_OBJECT  int  结果调用方式:$result->name
 */
define('DB_FETCH_ASSOC', 0);
define('DB_FETCH_NUM', 1);
define('DB_FETCH_BOTH', 2);
define('DB_FETCH_OBJECT', 3);
/*
 *定义默认序列发生器的名称
 */
define('DB_SEQUENCE_TABLENAME', 'sequences');

class Db{
    /*
     * 当前数据库联接选项
     */
    var $dbHost = DB_HOST;
    var $dbName = DB_NAME;
    var $dbType = 'Mysql';
    var $dbUser = DB_USER;
    var $dbPwd = DB_PWD;
    var $pcnn = DB_PCONNECT;
    /*
     * 当前数据库连接
     */
    var $cnn = '';
    /*
     * 数据查询结果的返回类型
     */
    var $queryFetchType = DB_FETCH_ASSOC;
    /*
     * 初始化函数
     */
 function Db(){
        $this->cnn = ($this->pcnn? mysql_connect($this->dbHost, $this->dbUser, $this->dbPwd):
                                                         mysql_connect($this->dbHost, $this->dbUser, $this->dbPwd))  or
                                                        $this->_halt('数据库连接错误');
        mysql_select_db($this->dbName, $this->cnn) or $this->_halt('数据库选择错误');
    }
    /*
     *  数据查询函数
     *
     * @param $sql        string  数据查询语句
     * @param $fetchType  int     数据查询结果的返回类型
     *
     * @return            array   数据查询结果
     */
    function &query($sql, $fetchType=DB_FETCH_ASSOC){
        $data = array();
        $rs = &mysql_query($sql, $this->cnn) or $this->_halt('数据查询错误', $sql);
        $exe = $this->_getCommand($fetchType);
        while($row=&$exe($rs))
        $data[] = &$row;
        return $data;
    }
    /*
     *  分页数据查询函数
     *
     * @param $sql        string  数据查询语句
     * @param $page       int     当前预查询页码
     * @param $pageSize   int     每页显示多少条纪录
     * @param $fetchType  int     数据查询结果的返回类型
     *
     *         数据查询结果,以及数据的分页信息
     * @return    array('pageSize'    => 每页显示的条数
     *                  'recordCount' => 总纪录数
     *                  'pageCount'   => 总页数
     *                  'page'        => 当前页码
     *                  'isFirst'     => 是否第一页
     *                  'isLast'      => 是否最后一页
     *                  'start'       => 返回结果的第一条纪录的序号
     *                  'sql'         => 查询的sql语句
     *                  'data'        => 查询得到的数据结果
     *                 )
     *                 数据查询结果,以及数据的分页信息
     */
    function &queryPage($sql, $page=1, $pageSize=20, $fetchType=DB_FETCH_ASSOC){
        $countSql = preg_replace('|SELECT.*FROM|i','SELECT COUNT(*) count FROM', $sql);
        $data['pageSize'] = (int)$pageSize        $data['recordCount'] = $this->getOne($countSql, 'count');
        $data['pageCount'] = ceil($data['recordCount']/$data['pageSize']);
        $data['page'] = $data['pageCount']==0? 0: ((int)$page        $data['page'] = $data['page']>$data['pageCount']? $data['pageCount']:$data['page'];
        $data['isFirst'] = $data['page']>1? false: true;
        $data['isLast'] = $data['page']        $data['start'] = ($data['page']==0)? 1: ($data['page']-1)*$data['pageSize']+1;
        $data['sql'] = $sql.' LIMIT '.($data['start']-1).','.$data['pageSize'];
        $data['data'] = &$this->query($data['sql'], $fetchType);
        return $data;
    }
    /*
     *  进行数据查询只返回第 1 行的数据
     *
     * @param $sql        string  数据查询语句
     * @param $fetchType  int     数据查询结果的返回类型
     *
     * @return            array   数据查询结果
     */
    function &queryRow($sql, $fetchType=DB_FETCH_ASSOC){
        $rs = &mysql_query($sql, $this->cnn) or $this->_halt('单行数据查询错误', $sql);
        $exe = $this->_getCommand($fetchType);
        return $exe($rs);
    }
    /*
     *  进行数据查询只返回第 1 行第 n 列的数据
     *
     * @param $sql        string  数据查询语句
     * @param $field      int     返回数据列的名称 或 数字序号
     *
     * @return            string  返回单个字段的值
     */
    function &getOne($sql, $field = 0){
        $rs = &mysql_query($sql, $this->cnn) or $this->_halt('单个数据查询错误', $sql);
        $row = mysql_fetch_array($rs);
        return $row[$field];
    }
    /*
     *  进行sql语句,包含 DELECT / INSERT / UPDATE.....的执行语句
     *
     * @param $sql        string  数据查询语句
     *
     * @return            string  返回该语句影响的数据行数
     */
    function execute($sql){
        $rs = mysql_query($sql) or $this->_halt('语句执行错误', $sql);
        return mysql_affected_rows($this->cnn);
    }
    /*
     *  得到最后一次插入数据的编号
     */
    function getInsertId(){
        return mysql_insert_id($this->cnn);
    }
    /*
     *  序列发生器,用来生成不重复的序列值
     *
     * @param $fieldName    string  序列的名称
     * @param $step         int     序列号间隔
     * @param $start        int     序列号的起始数值
     *
     * @return              int     新的序列值
     */
    function getSeq($fieldName, $step=1, $start=1){
        $table = DB_SEQUENCE_TABLENAME;
        $step = (int)$step;
        $start = (int)$start;
        $rs = mysql_query("UPDATE $table SET seq_num=seq_num+($step) WHERE seq_name='$fieldName'");
        if(!$rs || mysql_affected_rows($this->cnn)            $rs = mysql_query('SELECT * FROM '.DB_SEQUENCE_TABLENAME, $this->cnn);
            if(!$rs){
                $sql = "CREATE TABLE $table (
                               seq_name VARCHAR( 20 ) NOT NULL ,
                               seq_num BIGINT( 20 ) DEFAULT 1 NOT NULL ,
                               PRIMARY KEY (seq_name))";
                $rs = mysql_query($sql) or $this->_halt('创建序列发生器表失败', $sql);
            }
            $rs = mysql_query("INSERT INTO $table VALUES('$fieldName', $start)") or
                       $this->_halt('添加新序列错误', $sql);
            $seq = $start;
        }else{
            $seq = &$this->getOne("SELECT seq_num FROM $table WHERE seq_name='$fieldName'");
        }
        return $seq;
    }

    function _getCommand($fetchType){
        switch($fetchType){
            case DB_FETCH_ASSOC: $exe = 'mysql_fetch_assoc'; break;
            case DB_FETCH_NUM: $exe = 'mysql_fetch_row'; break;
            case DB_FETCH_BOTH: $exe = 'mysql_fetch_array'; break;
            case DB_FETCH_OBJECT: $exe = 'mysql_fetch_object'; break;
            default: $exe = 'mysql_fetch_array'; break;
        }
        return $exe;
    }

    function _halt($msg){
        $errNo = mysql_errno($this->cnn);
        $errStr = mysql_error($this->cnn);
        die("数据库错误:$msg
$errNo : $errStr");
    }
}
?>
 

 



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

See all articles