Home > php教程 > php手册 > php---数据库类封装

php---数据库类封装

WBOY
Release: 2016-06-13 09:35:58
Original
909 people have browsed it

为了节省以后的时间,今天封装了操作sql语句的一个类,在此保存起来,方面以后使用。

这个类的文件名:SqlTool.class.php

主要有dql和dml两个函数

看下面的源码“

<?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; //没有行数收到影响
            }
        }
        
     }
   } 

?>
Copy after login

演示一下使用方法:

<?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;
?>
Copy after login


Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template