好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

PHP封装数据库操作类 - php类库

PHP封装数据库操作类

我们在网站开发时比较合理的做法就是我们的常用的一些程序做成函数或封闭成类,这样可以重复利用,可以节约开发成本了,下面我来给各位介绍了我常使用的类.

有面向对象技术基础的编程人员看一天就可以写起来了,而PHP在访问数据库的时候又经常会出现各种问题,如字符编码问题、SQL语法错误问题、PHP处理数据记录对象和返回对象的问题等,我这里写了一个数据库操作类,封装了数据库增删添改等操作,很方便使用,用这个类,可以加速网站的后台开发.

优点:

1.方便快捷, 数据库操作只需调用接口;

2.统一编码(utf8),不易导致乱码

3.结构清晰. 如处理前端请求的后台程序(test.php) + 表封装类(user.class.php) + 数据库封装类(db.class.php) + 配置信息(configuration.php)

以下例子有四个文件:configuration.php + db.class.php + user.class.php + test.php,放在同一个目录下.

首先是一个数据库配置的文件类configuration.php,代码如下:

<?php         /**         * 数据库配置信息         */        define( 'DB_HOST' , 'localhost' );             //服务器        define( 'DB_USER' , 'root' );                  //数据库用户名        define( 'DB_PASSWORD' , '' );                  //数据库密码        define( 'DB_NAME' , 'test0' );                 //默认数据库        define( 'DB_CHARSET' , 'utf8' );               //数据库字符集        define( 'TIMEZONE' , "PRC" );                  //时区设置   ?> 

接下来就是数据库操作类db.class.php,代码如下:

<?php       require_once ( "./configuration.php" );    //引入配置常量文件       date_default_timezone_set(TIMEZONE);        /**     * 类名:DB     * 说明:数据库操作类     */     class  DB   {     public   $host ;             //服务器      public   $username ;         //数据库用户名      public   $password ;         //数据密码      public   $dbname ;           //数据库名      public   $conn ;             //数据库连接变量          /**      * DB类构造函数      */      public   function  DB( $host =DB_HOST , $username =DB_USER, $password =DB_PASSWORD, $dbname =DB_NAME)    {      $this ->host =  $host ;      $this ->username =  $username ;      $this ->password =  $password ;      $this ->dbname =  $dbname ;         }     /**      * 打开数据库连接      */      public   function  open()    {      $this ->conn = mysql_connect( $this ->host, $this ->username, $this ->password);     mysql_select_db( $this ->dbname);     mysql_query( "SET CHARACTER SET utf8" );    }     /**      * 关闭数据连接      */      public   function  close()    {     mysql_close( $this ->conn);    }     /**      * 通过sql语句获取数据      * @return: array()      */      public   function  getObjListBySql( $sql )    {      $this ->open();      $rs  = mysql_query( $sql , $this ->conn);      $objList  =  array ();      while ( $obj  = mysql_fetch_object( $rs ))     {       if ( $obj )      {        $objList [] =  $obj ;      }     }      $this ->close();      return   $objList ;    }            /**      * 向数据库表中插入数据      * @param:$table,表名      * @param:$columns,包含表中所有字段名的数组。默认空数组,则是全部有序字段名      * @param:$values,包含对应所有字段的属性值的数组      */      public   function  insertData( $table , $columns = array (), $values = array ())    {      $sql  =  'insert into ' . $table  . '( ' ;      for ( $i  = 0;  $i  < sizeof( $columns ); $i  ++)     {       $sql  .=  $columns [ $i ];       if ( $i  < sizeof( $columns ) - 1)      {        $sql  .=  ',' ;      }     }      $sql  .=  ') values ( ' ;       for ( $i  = 0;  $i  < sizeof( $values ); $i  ++)     {       $sql  .=  "'" . $values [ $i ]. "'" ;       if ( $i  < sizeof( $values ) - 1)      {        $sql  .=  ',' ;      }     }      $sql  .=  ' )' ;      $this ->open();     mysql_query( $sql , $this ->conn);      $id  = mysql_insert_id( $this ->conn);      $this ->close();      return   $id ;    }         /**      * 通过表中的某一属性获取数据      */      public   function  getDataByAtr( $tableName , $atrName , $atrValue ){     @ $data  =  $this ->getObjListBySql( "SELECT * FROM " . $tableName . " WHERE $atrName = '$atrValue'" );      if ( count ( $data )!=0) return   $data ;      return  NULL;  //开源代码phpfensi测试数据      }     /**      * 通过表中的"id",删除记录      */       public   function   delete ( $tableName , $atrName , $atrValue ){       $this ->open();       $deleteResult  = false;       if (mysql_query( "DELETE FROM " . $tableName . " WHERE $atrName = '$atrValue'" ))  $deleteResult  = true;       $this ->close();       if ( $deleteResult )  return  true;       else   return  false;      }     /**      * 更新表中的属性值      */       public   function  updateParamById( $tableName , $atrName , $atrValue , $key , $value ){       $db  =  new  DB();       $db ->open();       if (mysql_query( "UPDATE " . $tableName . " SET $key = '$value' WHERE $atrName = '$atrValue' " )){   //$key不要单引号         $db ->close();        return  true;      }       else {        $db ->close();        return  false;      }     }     /*       * @description: 取得一个table的所有属性名      * @param: $tbName 表名      * @return:字符串数组      */      public   function  fieldName( $tbName ){      $resultName = array ();      $i =0;      $this ->open();      $result  = mysql_query( "SELECT * FROM $tbName" );      while  ( $property  = mysql_fetch_field( $result )){       $resultName [ $i ++]= $property ->name;      }      $this ->close();      return   $resultName ;        }   }   ?> 

接下来是测试了,我在phpmyadmin中建了一个test0数据库,里面建一张表user,然后用php写一个user类对应数据库中的user表.

user.class.php,代码如下:

<?php          require_once ( "./db.class.php" );       class  User{      public   $name  = NULL;      public   $password  = NULL;           /**       * 构造函数       */       public   function  __construct( $name , $password ){       $this ->name =  $name ;       $this ->password =  $password ;      }        public   function  insert(){       $db  =  new  DB();          $resultid  =  $db ->insertData( "user" , array (), array ( '' , $this ->name, $this ->password));           return   $resultid ;      }          public   static   function  getUserById( $uid ){        $db  =  new  DB();        return   $db ->getDataByAtr( "user" , 'uid' , $uid );       }        public   static   function  getUserByName( $name ){        $db  =  new  DB();       @ $data  =  $db ->getObjListBySql( "SELECT * FROM user WHERE name = '$name'" );        if ( count ( $data )!=0) return   $data ;        else   return  null;       }        public   static   function  getAllUser(){        $db  =  new  DB();        @ $data  =  $db ->getObjListBySql( "SELECT * FROM user" );         if ( count ( $data )!=0)  return   $data ;         else   return  null;       }             public   static   function  deleteByUid( $uid ){        $admin  = Admin::getAdminById( $uid );        $db  =  new  DB();        if ( $db -> delete ( "user" , "uid" , $uid ))  return  true;        else   return  false;       }     }         ?> 

测试程序:test.php,代码如下:

<?php      header( "Content-Type:text/html; charset=utf8" );      require_once ( "./user.class.php" );      $user  =  new  User( "HelloWorld" , "123456" );    $user ->insert();      $users  = User::getAllUser();      foreach  ( $users   as   $u ) {     echo   "<br/>" . $u ->name. "<br/>" . $u ->password. "<br/>" ;   }  ?>

查看更多关于PHP封装数据库操作类 - php类库的详细内容...

  阅读:47次