search
Homephp教程php手册封装自己的DB类(PHP),封装db类php

封装自己的DB类(PHP),封装db类php

封装一个DB类,用来专门操作数据库,以后凡是对数据库的操作,都由DB类的对象来实现。这样有了自己的DB类,写项目时简单的sql语句就不用每次写了,直接调用就行,很方便!

1.封装一个DB类。一个类文件应该只有一个类,其他的内容全部都没有。类文件的命名规则:类名.class.php

下面是创建DB类的代码:

<?<span>php

    </span><span>//</span><span>封装一个DB类,用来专门操作数据库,以后凡是对数据库的操作,都由DB类的对象来实现</span>
    <span>class</span><span> DB{
        </span><span>//</span><span>属性</span>
        <span>private</span> <span>$host</span><span>;
        </span><span>private</span> <span>$port</span><span>;
        </span><span>private</span> <span>$user</span><span>;
        </span><span>private</span> <span>$pass</span><span>;
        </span><span>private</span> <span>$dbname</span><span>;
        </span><span>private</span> <span>$charset</span><span>;
        </span><span>private</span> <span>$prefix</span>;            <span>//</span><span>表前缀</span>
        <span>private</span> <span>$link</span>;                <span>//</span><span>连接资源(连接数据库,一般会返回一个资源,所以需要定义一个link属性)

        //构造方法(作用:为了初始化对象的属性),会被自动调用</span>
        <span>/*</span><span>
         * @param1 array $arr,默认为空,里面是一个关联数组,里面有7个元素
         * array('host' => 'localhost','port' => '3306');
         </span><span>*/</span>
        <span>public</span> <span>function</span> __construct(<span>$arr</span> = <span>array</span><span>()){
            </span><span>//</span><span>初始化</span>
            <span>$this</span>->host = <span>isset</span>(<span>$arr</span>['host']) ? <span>$arr</span>['host'] : 'localhost';<span>//</span><span>先判断是否有自己的host,如果有就用自己的host,否则就使用默认的localhost</span>
            <span>$this</span>->port = <span>isset</span>(<span>$arr</span>['port']) ? <span>$arr</span>['port'] : '3306'<span>;
            </span><span>$this</span>->user = <span>isset</span>(<span>$arr</span>['user']) ? <span>$arr</span>['user'] : 'root'<span>;
            </span><span>$this</span>->pass = <span>isset</span>(<span>$arr</span>['pass']) ? <span>$arr</span>['pass'] : 'root'<span>;
            </span><span>$this</span>->dbname = <span>isset</span>(<span>$arr</span>['dbname']) ? <span>$arr</span>['dbname'] : 'mydatabase'<span>;
            </span><span>$this</span>->charset = <span>isset</span>(<span>$arr</span>['charset']) ? <span>$arr</span>['charset'] : 'utf8'<span>;
            </span><span>$this</span>->prefix = <span>isset</span>(<span>$arr</span>['prefix']) ? <span>$arr</span>['prefix'] : ''<span>;

            </span><span>//</span><span>连接数据库(类是要操作数据库,因此要连接数据库)</span>
            <span>$this</span>-><span>connect();

            </span><span>//</span><span>设置字符集</span>
            <span>$this</span>-><span>setCharset();

            </span><span>//</span><span>选择数据库</span>
            <span>$this</span>-><span>setDbname();
        }

        </span><span>/*</span><span>
         * 连接数据库
        </span><span>*/</span>
        <span>private</span> <span>function</span><span> connect(){
            </span><span>//</span><span>mysql扩展连接</span>
            <span>$this</span>->link = <span>mysql_connect</span>(<span>$this</span>->host . ':' . <span>$this</span>->port,<span>$this</span>->user,<span>$this</span>-><span>pass);

            </span><span>//</span><span>判断结果</span>
            <span>if</span>(!<span>$this</span>-><span>link){
                </span><span>//</span><span>结果出错了
                //暴力处理,如果是真实线上项目(生产环境)必须写入到日志文件</span>
                <span>echo</span> '数据库连接错误:<br/>'<span>;
                </span><span>echo</span> '错误编号' . <span>mysql_errno</span>() . '<br/>'<span>;
                </span><span>echo</span> '错误内容' . <span>mysql_error</span>() . '<br/>'<span>;
                </span><span>exit</span><span>;
            }
        }

        </span><span>/*</span><span>
         * 设置字符集
        </span><span>*/</span>
        <span>private</span> <span>function</span><span> setCharset(){
            </span><span>//</span><span>设置</span>
            <span>$this</span>->db_query("set names {<span>$this</span>->charset}"<span>);
        }

        </span><span>/*</span><span>
         * 选择数据库
        </span><span>*/</span>
        <span>private</span> <span>function</span><span> setDbname(){
            </span><span>$this</span>->db_query("use {<span>$this</span>->dbname}"<span>);
        }

        </span><span>/*</span><span>
         * 增加数据
         * @param1 string $sql,要执行的插入语句
         * @return boolean,成功返回是自动增长的ID,失败返回FALSE
        </span><span>*/</span>
        <span>public</span> <span>function</span> db_insert(<span>$sql</span><span>){
            </span><span>//</span><span>发送数据</span>
            <span>$this</span>->db_query(<span>$sql</span><span>);
            
            </span><span>//</span><span>成功返回自增ID</span>
            <span>return</span> <span>mysql_affected_rows</span>() ? <span>mysql_insert_id</span>() : <span>FALSE</span><span>;
        }

        </span><span>/*</span><span>
         * 删除数据
         * @param1 string $sql,要执行的删除语句
         * @return Boolean,成功返回受影响的行数,失败返回FALSE
        </span><span>*/</span>
        <span>public</span> <span>function</span> db_delete(<span>$sql</span><span>){
            </span><span>//</span><span>发送SQL</span>
            <span>$this</span>->db_query(<span>$sql</span><span>);

            </span><span>//</span><span>判断结果</span>
            <span>return</span> <span>mysql_affected_rows</span>() ? <span>mysql_affected_rows</span>() : <span>FALSE</span><span>;
        }

        </span><span>/*</span><span>
         * 更新数据
         * @param1 string $sql,要执行的更新语句
         * @return Boolean,成功返回受影响的行数,失败返回FALSE
        </span><span>*/</span>
        <span>public</span> <span>function</span> db_update(<span>$sql</span><span>){
            </span><span>//</span><span>发送SQL</span>
            <span>$this</span>->db_query(<span>$sql</span><span>);

            </span><span>//</span><span>判断结果</span>
            <span>return</span> <span>mysql_affected_rows</span>() ? <span>mysql_affected_rows</span>() : <span>FALSE</span><span>;
        }

        </span><span>/*</span><span>
         * 查询:查询一条记录
         * @param1 string $sql,要查询的SQL语句
         * @return mixed,成功返回一个数组,失败返回FALSE
        </span><span>*/</span>
        <span>public</span> <span>function</span> db_getRow(<span>$sql</span><span>){
            </span><span>//</span><span>发送SQL</span>
            <span>$res</span> = <span>$this</span>->db_query(<span>$sql</span><span>);

            </span><span>//</span><span>判断返回</span>
            <span>return</span> <span>mysql_num_rows</span>(<span>$res</span>) ? <span>mysql_fetch_assoc</span>(<span>$res</span>) : <span>FALSE</span><span>;
        }

        </span><span>/*</span><span>
         * 查询:查询多条记录
         * @param1 string $sql,要查询的SQL语句
         * @return mixed,成功返回一个二维数组,失败返回FALSE
        </span><span>*/</span>
        <span>public</span> <span>function</span> db_getAll(<span>$sql</span><span>){
            </span><span>//</span><span>发送SQL</span>
            <span>$res</span> = <span>$this</span>->db_query(<span>$sql</span><span>);

            </span><span>//</span><span>判断返回</span>
            <span>if</span>(<span>mysql_num_rows</span>(<span>$res</span><span>)){
                </span><span>//</span><span>循环遍历</span>
                <span>$list</span> = <span>array</span><span>();
                
                </span><span>//</span><span>遍历</span>
                <span>while</span>(<span>$row</span> = <span>mysql_fetch_assoc</span>(<span>$res</span><span>)){
                    </span><span>$list</span>[] = <span>$row</span><span>;
                }

                </span><span>//</span><span>返回</span>
                <span>return</span> <span>$list</span><span>;
            }

            </span><span>//</span><span>返回FALSE</span>
            <span>return</span> <span>FALSE</span><span>;
        }

        </span><span>/*</span><span>
         * mysql_query错误处理
         * @param1 string $sql,需要执行的SQL语句
         * @return mixed,只要语句不出错,全部返回
        </span><span>*/</span>
        <span>private</span> <span>function</span> db_query(<span>$sql</span><span>){
            </span><span>//</span><span>发送SQL</span>
            <span>$res</span> = <span>mysql_query</span>(<span>$sql</span><span>);

            </span><span>//</span><span>判断结果</span>
            <span>if</span>(!<span>$res</span><span>){
                </span><span>//</span><span>结果出错了
                //暴力处理,如果是真实线上项目(生产环境)必须写入到日志文件</span>
                <span>echo</span> '语句出现错误:<br/>'<span>;
                </span><span>echo</span> '错误编号' . <span>mysql_errno</span>() . '<br/>'<span>;
                </span><span>echo</span> '错误内容' . <span>mysql_error</span>() . '<br/>'<span>;
                </span><span>exit</span><span>;
            }
            </span><span>//</span><span>没有错误</span>
            <span>return</span> <span>$res</span><span>;
        }
            </span><span>//</span><span>__sleep方法</span>
        <span>public</span> <span>function</span><span> __sleep(){
            </span><span>//</span><span>返回需要保存的属性的数组</span>
            <span>return</span> <span>array</span>('host','port','user','pass','dbname','charset','prefix'<span>);
        }

        </span><span>//</span><span>__wakeup方法</span>
        <span>public</span> <span>function</span><span> __wakeup(){
            </span><span>//</span><span>连接资源</span>
            <span>$this</span>-><span>connect();
            </span><span>//</span><span>设置字符集和选中数据库</span>
            <span>$this</span>-><span>setCharset();
            </span><span>$this</span>-><span>setDbname();
        }    

        </span><span>/*</span><span>
         * 获取完整的表名
        </span><span>*/</span>
        <span>protected</span> <span>function</span><span> getTableName(){
            </span><span>//</span><span>完整表名:前缀+表名</span>
            <span>return</span> <span>$this</span>->prefix . <span>$this</span>-><span>table;
        }
    }
</span><span>//</span><span>这个DB类,一般不写析构(不释放资源)    </span>

2.使用DB类,但是如果要使用某一个类来创建对象,必须要保证该类已经被加载到代码区里。可以使用一个魔术函数来实现对类的自动加载

自动加载:当一个脚本文件在执行某些语句的时候(实例化)需要去代码区里寻找对应的类,如果找不到会通过自动加载函数来将对应的类文件进行加载。

魔术函数__autoload()

比如我们在index.php页面中需要使用DB类,那么我们就直接调用即可,具体代码如下:

<?<span>php
    </span><span>//</span><span>使用DB类的对象来访问数据库
    //先加载类文件
    //include_once 'DB.class.php';
        //如果想使用其他类,又需要加载(所以使用魔术函数__autoload来实现类的自动加载)
    //显示的写出魔术函数__autoload
    //参数:需要加载的类的名字</span>
    <span>function</span> __autoload(<span>$a</span><span>){
        </span><span>//</span><span>将对应的类文件加载进来</span>
        <span>if</span>(<span>is_file</span>("<span>$a</span>.class.php"<span>)){
            </span><span>include_once</span> "<span>$a</span>.class.php"<span>;
        }
    }
    </span><span>//</span><span>实例化</span>
    <span>$db</span> = <span>new</span> DB(<span>array</span>('dbname' => 'mydatabase'<span>));

    
    </span>

 

Statement
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
thinkphp是不是国产框架thinkphp是不是国产框架Sep 26, 2022 pm 05:11 PM

thinkphp是国产框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。

一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列Apr 20, 2022 pm 01:07 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了关于使用think-queue来实现普通队列和延迟队列的相关内容,think-queue是thinkphp官方提供的一个消息队列服务,下面一起来看一下,希望对大家有帮助。

thinkphp的mvc分别指什么thinkphp的mvc分别指什么Jun 21, 2022 am 11:11 AM

thinkphp基于的mvc分别是指:1、m是model的缩写,表示模型,用于数据处理;2、v是view的缩写,表示视图,由View类和模板文件组成;3、c是controller的缩写,表示控制器,用于逻辑处理。mvc设计模式是一种编程思想,是一种将应用程序的逻辑层和表现层进行分离的方法。

实例详解thinkphp6使用jwt认证实例详解thinkphp6使用jwt认证Jun 24, 2022 pm 12:57 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了使用jwt认证的问题,下面一起来看一下,希望对大家有帮助。

thinkphp扩展插件有哪些thinkphp扩展插件有哪些Jun 13, 2022 pm 05:45 PM

thinkphp扩展有:1、think-migration,是一种数据库迁移工具;2、think-orm,是一种ORM类库扩展;3、think-oracle,是一种Oracle驱动扩展;4、think-mongo,一种MongoDb扩展;5、think-soar,一种SQL语句优化扩展;6、porter,一种数据库管理工具;7、tp-jwt-auth,一个jwt身份验证扩展包。

一文教你ThinkPHP使用think-queue实现redis消息队列一文教你ThinkPHP使用think-queue实现redis消息队列Jun 28, 2022 pm 03:33 PM

本篇文章给大家带来了关于ThinkPHP的相关知识,其中主要整理了使用think-queue实现redis消息队列的相关问题,下面一起来看一下,希望对大家有帮助。

thinkphp 怎么查询库是否存在thinkphp 怎么查询库是否存在Dec 05, 2022 am 09:40 AM

thinkphp查询库是否存在的方法:1、打开相应的tp文件;2、通过“ $isTable=db()->query('SHOW TABLES LIKE '."'".$data['table_name']."'");if($isTable){...}else{...}”方式验证表是否存在即可。

thinkphp3.2怎么关闭调试模式thinkphp3.2怎么关闭调试模式Apr 25, 2022 am 10:13 AM

在thinkphp3.2中,可以利用define关闭调试模式,该标签用于变量和常量的定义,将入口文件中定义调试模式设为FALSE即可,语法为“define('APP_DEBUG', false);”;开启调试模式将参数值设置为true即可。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),