封装数据库操作类

目录

封装数据库操作类


1.创建文件  DB.class.php;

2.定义属性,为了增加类对成员的控制,我们一般使用访问修饰限定符来保护类结构完整性。(private>protected>public);

3.初始化属性,构造方法来进行初始化;

4.连接数据库,定义成方法;

5.设置字符集,定义成方法;

6.选择数据库,定义成方法;

7.执行sql语句的方法;

8.增加的方法;

9.删除的方法;

10.修改的方法;

11.查询一条数据的方法;

12.查询多条语句的方法;

 关于是否在类中定义属性的原则: 如果在类成员中,如果有多个地方需要使用到同一变量,我们一般把该变量定义为该类的属性;

封装数据库操作类

<?php
    header('content-type:text/html;charset=utf-8');
    //封装数据库操作类
	 class  DB
	 {
	      //定义常用的属性  
		  private $host;
		  private $port;
		  private $user;
		  private $password;
		  private $charset;
		  private $database;
	     
		 //定义一个构造方法进行初始化设置
		 /**
         *@parameter1  $arr=array()  数组里面保存数据库里面相应属性的内容
         *  $arr=['host'=>'localhost','port'=>3306,'user'=>'root','password'=>'root',
         *  'charset'=>'utf8','database'=>'cms']
		 */

		  public function __construct($arr=array()){
		       $this->host=isset($arr['host'])?  $arr['host'] : 'localhost';
		       $this->port=isset($arr['port'])?  $arr['port'] : '3306';
		       $this->user=isset($arr['user'])?  $arr['user'] : 'root';
		       $this->password=isset($arr['password'])?  $arr['password'] : 'root';
		       $this->charset=isset($arr['charset'])?  $arr['charset'] : 'utf8';
		       $this->database=isset($arr['database'])?  $arr['database'] : 'php';
               //调用连接数据库的方法
			   $this->db_connect();
			   //调用设置字符集的方法
			   $this->db_charset();
			   //调用选择数据库的方法
			   $this->db_database();
		  }

        /*连接数据库的方法  
        *原则:在内部能用私有或者受保护的尽量 尽量不让此方法暴露在类的外部,保证类的完整性及安全
		*/
		private function db_connect(){
		      @$link=mysql_connect($this->host.":".$this->port,$this->user,$this->password);
              if(!$link){
			     echo '数据库连接失败<br>';
			     echo '错误编号是'.mysql_errno().'<br>';
                 echo  '错误信息是'.iconv('gbk','utf-8',mysql_error());
				 exit;
			  }
		 }
      
	    //设置字符编码

		 private function db_charset(){
			 $this->db_query("set names {$this->charset}");
			/*
		    $res=mysql_query("set names {$this->charset}");
			if(!$res){
			     echo 'sql语句执行失败<br>';
			     echo '错误编号是'.mysql_errno().'<br>';
                 echo  '错误信息是'.iconv('gbk','utf-8',mysql_error());
				 exit;
			  }
			*/		 
		 }

		 //选择数据库

		private function db_database(){
			$this->db_query("use {$this->database}");
			/*
		     $res=mysql_query("use {$this->database}");
		     if(!$res){
			     echo 'sql语句执行失败<br>';
			     echo '错误编号是'.mysql_errno().'<br>';
                 echo  '错误信息是'.iconv('gbk','utf-8',mysql_error());
				 exit;
			  }
			 */
		 }
         
         /*
            //执行sql语句的方法  每条SQL语句在执行过程中都可能因为sql语句有误而导致执行失败
			@param1  $sql  要执行的sql语句
			@return  $res   写操作返回bool类型 ,读操作返回结果集资源或者bool类型的false
		 */

		  private function db_query($sql){
		      $res=mysql_query($sql);
		      if(!$res){
			     echo 'sql语句执行失败<br>';
			     echo '错误编号是'.mysql_errno().'<br>';
                 echo  '错误信息是'.iconv('gbk','utf-8',mysql_error());
				 exit;
			  }
		     return $res;
		  }

		  /* 
		    插入数据操作方法
            @param1 $sql  要执行的sql语句
			@return  $id  返回执行自增ID
		  */

		  protected function db_insert($sql){
			 /*
		     $res=mysql_query($sql);   //mysql_query()执行正确的sql语句
			 if(!$res){
			     echo 'sql语句执行失败<br>';
			     echo '错误编号是'.mysql_errno().'<br>';
                 echo  '错误信息是'.iconv('gbk','utf-8',mysql_error());
				 exit;
			  }
			 */
			 if($this->db_query($sql)){
			    //获取自增ID
				 $id=mysql_insert_id();
				 return $id;
			 }  
		  }
        
	    /*
			* 删除操作
			* @param1  $sql  要删除的sql语句
            * @return  $rows  受影响的行数
		*/
        protected function db_delete($sql){
		   $res=$this->db_query($sql);
		   if($res){
		      //获取受影响的行数
		      $rows=mysql_affected_rows();
			  return $rows;
		   }
		
		}

        /*
			* 修改操作
			* @param1  $sql  要删除的sql语句
            * @return  $rows  受影响的行数
		*/
       protected function db_update($sql){
		   $res=$this->db_query($sql);
		   if($res){
		      //获取受影响的行数
		      $rows=mysql_affected_rows();
			  return $rows;
		   }
		
		}

        /*
           *  查询一条结果
           * @parameter1  $sql  查询的语句
		   * @return  $result   返回的一维关联数组
		*/

		 protected function db_selectOne($sql){
		   $res=$this->db_query($sql);
		   if($res){
		      $result=mysql_fetch_assoc($res);
		      return $result;
		   }
		}

		/*
           *  查询多条结果
           * @parameter1  $sql  查询的语句
		   * @return  $arr   返回的二维关联数组
		*/

		 protected function db_selectAll($sql){
		   $res=$this->db_query($sql);
		   if($res){
		      while($row=mysql_fetch_assoc($res)){
			     $arr[]=$row;
			  }
             return $arr;
		   }
		} 
      //这是类的结束
	 }

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是更详细的步骤: (1) 创建Sql.php文件 在你的项目中创建一个名为Sql.php的文件,用于封装数据库操作。 (2) 创建构造方法 在Sql.php文件中创建一个构造方法,用于初始化数据库信息。你需要传递以下参数: - 主机名 - 用户名 - 密码 - 数据库名 ``` class Sql { private $host; private $username; private $password; private $dbname; public function __construct($host, $username, $password, $dbname) { $this->host = $host; $this->username = $username; $this->password = $password; $this->dbname = $dbname; } } ``` (3) 创建connect0方法 在Sql.php文件中创建一个connect0方法,用于连接数据库。连接成功后,返回连接对象。 ``` class Sql { private $host; private $username; private $password; private $dbname; private $conn; public function __construct($host, $username, $password, $dbname) { $this->host = $host; $this->username = $username; $this->password = $password; $this->dbname = $dbname; } public function connect0() { $this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->dbname); if (!$this->conn) { die("Connection failed: " . mysqli_connect_error()); } return $this->conn; } } ``` (4) 封装执行读写操作的方法 在Sql.php文件中创建一个execute方法,用于执行读写操作。你需要传递以下参数: - SQL语句 - 是否为查询语句 如果是查询语句,返回查询结果。如果是更新语句,返回受影响的行数。 ``` class Sql { private $host; private $username; private $password; private $dbname; private $conn; public function __construct($host, $username, $password, $dbname) { $this->host = $host; $this->username = $username; $this->password = $password; $this->dbname = $dbname; } public function connect0() { $this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->dbname); if (!$this->conn) { die("Connection failed: " . mysqli_connect_error()); } return $this->conn; } public function execute($sql, $is_query) { $result = mysqli_query($this->conn, $sql); if (!$result) { die("Error executing query: " . mysqli_error($this->conn)); } if ($is_query) { $rows = array(); while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } return $rows; } else { return mysqli_affected_rows($this->conn); } } } ``` (5) 在浏览器中查看运行结果 在你的项目中创建一个test.php文件,用于测试Sql的功能。在test.php文件中,先实例化Sql,然后连接数据库,并执行一个查询语句。 ``` require_once('Sql.php'); $sql = new Sql('localhost', 'username', 'password', 'dbname'); $conn = $sql->connect0(); $result = $sql->execute("SELECT * FROM users", true); var_dump($result); ``` 在浏览器中打开test.php文件,你应该能够看到从数据库中查询到的用户数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值