Home  >  Article  >  Backend Development  >  About the method of establishing encapsulation of database access class in PHP

About the method of establishing encapsulation of database access class in PHP

一个新手
一个新手Original
2017-09-12 10:45:461186browse

Establish an encapsulation of the database access class

<?php
 class DBDA
{
    public $host = "localhost"; //服务器地址
    public $uid = "root"; //数据库的用户名
    public $pwd = ""; //数据库的密码
    public $dbname = "";//数据库名
     
    //执行SQL语句,返回相应结果的函数
    //$sql是要执行的SQL语句
    //$type是SQL语句的类型,0代表增删改,1代表查询
    //$db代表要操作的数据库
    public function Query($sql,$type=1,$db="xm_youxiang")
    {
        //造连接对象
        $conn = new MySQLi($this->host,$this->uid,$this->pwd,$db);
         
        //判断连接是否成功
        !mysqli_connect_error() or die("连接失败!");
         
        //执行SQL语句
        $result = $conn->query($sql);
         
        //判断SQL语句类型
        if($type==1)
        {
            //如果是查询语句返回结果集的二维数组
            return $result->fetch_all();
        }
        else
        {
            //如果是其他语句,返回true或false
            return $result;
        }
    }

The above is the detailed content of About the method of establishing encapsulation of database access class in PHP. For more information, please follow other related articles on the PHP Chinese website!

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