Home >Backend Development >PHP Tutorial >php---Database class encapsulation_PHP tutorial

php---Database class encapsulation_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:30:35775browse

In order to save time in the future, today I have encapsulated a class for operating SQL statements and save it here for future use.

The file name of this class: SqlTool.class.php

There are mainly two functions: dql and dml

Look at the source code below”

<?php

   class SqlTool{
      private $conn;
      private $username="root";
      private $password="1234";
      private $host="127.0.0.1";
      private $db="test";
     
     function SqlTool(){
        $this->conn=mysql_connect($this->host,$this->username,$this->password);
        if(!$this->conn)
        {
            die  ("连接失败".mysql_error($this.conn));
        }
        mysql_select_db($this->db,$this->conn);
        mysql_query("set names utf8");
     }
     
     //完成select
     function execute_dql($sql)
     {
        $result = mysql_query($sql,$this->conn);
        $arrTemp = array();
        $counter = 0;
        while($row = mysql_fetch_assoc($result))
        {
         $arrTemp[$counter] = $row;
          $counter++;
        }
        mysql_free_result($result);
        mysql_close($this->conn);
        
        return json_encode($arrTemp);
     }
     
     //完成dml
     public  function execute_dml($sql)
     {
        $res=mysql_query($sql,$this->conn);
        if(!$res)
        {
            return 0; //执行失败
        } 
        else
        {
            if(mysql_affected_rows($this->conn)>0)
            { 
                return 1;  //执行成功
            } 
            else
            {
                return 2; //没有行数收到影响
            }
        }
        
     }
   } 

?>

Demonstrate how to use:

<?php
 
  @header("content-Type:text/html;charset:utf-8");
 
  require_once "SqlTool.class.php";
  $sqlStr = "insert into student(number,name,age) values('200911230','huzhuxi','45');";
  $sqlTool = new SqlTool();
  $result1=$sqlTool->execute_dml($sqlStr);
  echo "结果为:".$result1."<br/>";
  
  $sqlStr1 = "select * from student";
  $resultStr = $sqlTool->execute_dql($sqlStr1);
  echo "当前数据:<br/>".$resultStr;
?>


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/765068.htmlTechArticleIn order to save time in the future, today I have encapsulated a class for operating sql statements. Save it here for future use. . The file name of this class: SqlTool.class.php mainly includes dql and dml...
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