Discuz教程网

功能强大的MySQL数据库操作类

[复制链接]
authicon kooness 发表于 2010-12-3 19:06:28 | 显示全部楼层 |阅读模式
主要功能有:MySQL常用操作、分页、导入与导出SQL文件、获取IP、MySQL错误提示等,相关的图片、css和js都已经放在附件里面了,自己下载研究吧!

有人问CSS和JS文件的作用,我做个说明吧!
CSS主要是用于错误提示和分页,下面是效果图:
分页


错误提示

JS主要用于分页里面的跳转功能(后面的输入框)
  1. <?php
  2. /**
  3. ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
  4. 【类 名】: MySql
  5. 【功 能】: mysql数据库操作类
  6. 【作 者】: Riyan
  7. 【日 期】: 2010/5/8
  8. 【版 本】: version 2.2c
  9. ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
  10. **/
  11. header('Content-Type:text/html; charset=utf-8');
  12. strtolower(basename($_SERVER['PHP_SELF'])) == 'mysql.inc.php' && header('Location:http://' . $_SERVER['HTTP_HOST']); //禁止直接访问本页

  13. class MySql{
  14.     private $host;                    // 数据库主机.
  15.     private $user;                    // 数据库用户名.
  16.     private $pass;                    // 数据库密码.
  17.     private $data;                    // 数据库名.
  18.     private $conn;                    // 数据库连接标识,0为mysql_connect,1为mysql_pconnect.
  19.     private $sql;                    // sql语句.
  20.     private $code;                    // 数据库编码,GBK,UTF8,GB2312.
  21.     public  $result;                // 执行query命令的结果数据集.

  22.     public  $errTip   = 'on';        // 是否开启错误提示,具有安全隐患,默认开启,建议仅在本地调试时使用.
  23.     public  $errLog   = 'on';        // 是否开启错误日志,默认开启,推荐开启.
  24.     public  $errDir   = 'error';    // 错误日志保存路径,须开启错误日志才有效,可以在类实例化以后自定义.

  25.     public  $numRows  = 0;            // 总记录.
  26.     private $pageAll  = 1;            // 总页数.
  27.     private $pageNow  = 1;            // 当前页.
  28.     private $pageSize = 10;            // 每页显示记录条数.

  29.     /*------------------------------------------------------------------
  30.      * 函数名:    __construct($host, $user, $pass, $data, $code, $conn)
  31.      * 作 用:    构造函数
  32.      * 参 数:    $host 数据库主机地址(必填)
  33.                 $user 数据库用户名(必填)
  34.                 $pass 数据库密码(必填)
  35.                 $data 数据库名(必填)
  36.                 $code 数据库编码(必填,默认为utf8)
  37.                 $conn 数据库连接标识,0(默认)为mysql_connect,1为mysql_pconnect(选填)
  38.      * 返回值:    无
  39.      * 实 例:    无
  40.     -------------------------------------------------------------------*/
  41.     public function __construct($host = 'localhost', $user = 'root', $pass = '', $data = '', $code = 'utf8', $conn = 0) {
  42.         $this->host = $host;
  43.         $this->user = $user;
  44.         $this->pass = $pass;
  45.         $this->data = $data;
  46.         $this->conn = $conn;
  47.         $this->code = $code;
  48.         $this->connect();
  49.     }

  50.     // 访问一个对象并不拥有的属性(私有属性)
  51.     public function __get($property) {
  52.         return $this->$property;
  53.     }

  54.     // 设置一个对象并不拥有的属性(私有属性)
  55.     public function __set($property, $value) {
  56.         $this->$property = $value;
  57.     }

  58.     // 数据库连接
  59.     private function connect() {
  60.         if ($this->conn == 1) {
  61.             $this->conn = mysql_pconnect($this->host, $this->user, $this->pass); // 永久链接
  62.         } else {
  63.             $this->conn = mysql_connect($this->host, $this->user, $this->pass);  // 临时链接
  64.         }
  65.         if (!$this->conn) {
  66.             $this->showError('无法连接服务器');
  67.         }
  68.         $this->selectDb($this->data);
  69.         $this->query("SET NAMES {$this->code}");
  70.         $this->query("SET CHARACTER_SET_CLIENT={$this->code}");
  71.         $this->query("SET CHARACTER_SET_RESULTS={$this->code}");
  72.     }

  73.     // 数据库选择
  74.     public function selectDb($db = '') {
  75.         if (empty($db)) {
  76.             $this->showError('未设置数据库名称');
  77.         }
  78.         $result = mysql_select_db($db, $this->conn);
  79.         if (!$result) {
  80.             $this->showError('无法连接数据库'.$db);
  81.         }
  82.         return $result;
  83.     }

  84.     /*------------------------------------------------------------------
  85.      * 函数名:    getInfo($type)
  86.      * 作 用:    取得 MySQL 服务器信息
  87.      * 参 数:    $type 要获取的信息类型(选填)
  88.      * 返回值:    字符串
  89.      * 实 例:    无
  90.     -------------------------------------------------------------------*/
  91.     public function getInfo($type = 0) {
  92.         switch ($type) {
  93.             case 1  : return mysql_get_host_info();   // 取得 MySQL 主机信息
  94.             case 2  : return mysql_get_proto_info();  // 取得 MySQL 协议信息
  95.             case 3  : return mysql_get_server_info(); // 取得 MySQL 服务器信息
  96.             default : return mysql_get_client_info(); // 取得 MySQL 客户端信息
  97.         }
  98.     }

  99.     /*------------------------------------------------------------------
  100.      * 函数名:    query($sql)
  101.      * 作 用:    数据库执行语句,可执行查询添加修改删除等任何sql语句
  102.      * 参 数:    $sql sql语句(必填)
  103.      * 返回值:    布尔
  104.      * 实 例:    无
  105.     -------------------------------------------------------------------*/
  106.     public function query($sql) {
  107.         $sql = trim($sql);
  108.         if (empty($sql)) {
  109.             $this->showError('SQL语句为空');
  110.         }
  111.         $this->sql = $sql;
  112.         $this->result = mysql_query($this->sql, $this->conn);
  113.         if (!$this->result) {
  114.             $this->showError('SQL语句有误', true);
  115.         }
  116.         return $this->result;
  117.     }

  118.     /*------------------------------------------------------------------
  119.      * 函数名:    createDataBase($db)
  120.      * 作 用:    创建添加新的数据库
  121.      * 参 数:    $db 数据库名称(必填)
  122.      * 返回值:    字符串
  123.      * 实 例:    无
  124.     -------------------------------------------------------------------*/
  125.     public function createDataBase($db = '') {
  126.         if (empty($db)) {
  127.             $this->showError('未设置待添加的数据库名称');
  128.         }
  129.         $this->query("CREATE DATABASE `{$db}`");
  130.     }

  131.     // 列出当前服务器中的所有数据库
  132.     public function listDataBase() {
  133.         $list = array();
  134.         $this->query('SHOW DATABASES');
  135.         while ($row = $this->fetch()) {
  136.             $list[] = $row['Database'];
  137.         }
  138.         return $list;
  139.     }

  140.     // 列出数据库中的所有表
  141.     public function listTables($db = '') {
  142.         $list = array();
  143.         if (!empty($db)) {
  144.             $db = ' FROM `'.$db.'`';
  145.         }
  146.         $this->query('SHOW TABLES'.$db);
  147.         while ($row = $this->fetch('', 2)) {
  148.             $list[] = $row[0];
  149.         }
  150.         return $list;
  151.     }
  152.    
  153.     // 列出表中的所有字段名
  154.     public function listFields($db = '', $tb = '') {
  155.         if (empty($table)) {
  156.             return false;
  157.         }
  158.         if (empty($db)) {
  159.             $db = $this->data;
  160.         }
  161.         $fields = mysql_list_fields($db, $tb, $this->conn);
  162.         $column = mysql_num_fields($fields);
  163.         $list   = array();        
  164.         for ($i = 0; $i < $column; $i++) {
  165.             $list[] = mysql_field_name($list, $i);
  166.         }
  167.         return $list;
  168.     }

  169.     /*------------------------------------------------------------------
  170.      * 函数名:    copyTable($dstTable, $srcTable, $condition)
  171.      * 作 用:    复制表
  172.      * 参 数:    $dstTable 待复制表的表名(必填)
  173.                 $srcTable 新表名(必填)
  174.                 $condition 复制条件(选填)
  175.      * 返回值:    布尔
  176.      * 实 例:    无
  177.     -------------------------------------------------------------------*/
  178.     public function copyTable($dstTable, $srcTable, $condition = '') {
  179.         return $this->query("SELECT * INTO `{$dstTable}` FROM `{$srcTable}` {$condition}");
  180.     }

  181.     /*------------------------------------------------------------------
  182.      * 函数名:    dropTable($table)
  183.      * 作 用:    删除表(请慎用,无法恢复)
  184.      * 参 数:    $table 要删除的表名,多个表请用数组,为空表示保存所有表信息(选填)
  185.      * 返回值:    无
  186.      * 实 例:    $DB->dropTable('mydb')
  187.     -------------------------------------------------------------------*/
  188.     public function dropTable($table = '') {
  189.         if (!is_array($table)) {
  190.             $table = empty($table) ? $this->listTables($this->data) : array($table);
  191.         }
  192.         foreach ($table as $tb) {
  193.             $this->query("DROP TABLE IF EXISTS `{$tb}`");
  194.         }
  195.     }

  196.     /*------------------------------------------------------------------
  197.      * 函数名:    getData($table, $fileds, $condition, $rows)
  198.      * 作 用:    查询数据
  199.      * 参 数:    $table 表名(必填)
  200.                 $fileds 字段名,默认为所有(选填)
  201.                 $condition 查询条件(选填)
  202.                 $rows 待查询记录条数,为0表示不限制(选填)
  203.      * 返回值:    布尔
  204.      * 实 例:    $DB->getData('mydb','user,password','order by id desc',10)
  205.     -------------------------------------------------------------------*/
  206.     public function getData($table, $fileds = '', $condition = '', $rows = 0) {
  207.         $table = '`'.strtr($table, array(' ' => '', '.' => '`.`', ',' => '`, `')).'`';
  208.         if (empty($fileds)) {
  209.             $fileds = '*';
  210.         }
  211.         if ($rows > 0) {
  212.             $condition .= " LIMIT 0,{$rows}";
  213.         }
  214.         $sql = "SELECT {$fileds} FROM {$table} {$condition}";
  215.         $res = $this->query($sql);
  216.         $this->numRows();
  217.         return $res;
  218.     }

  219.     // 只查询一条记录,返回关联数组
  220.     public function getRows($table, $fileds = '*', $condition = '') {
  221.         $table = '`'.strtr($table, array(' ' => '', '.' => '`.`', ',' => '`, `')).'`';
  222.         if (empty($fileds)) {
  223.             $fileds = '*';
  224.         }
  225.         $this->query("SELECT {$fileds} FROM {$table} {$condition} LIMIT 0,1");
  226.         return $this->fetch();
  227.     }

  228.     /*------------------------------------------------------------------
  229.      * 函数名:    addData($table, $data, $values)
  230.      * 作 用:    添加数据
  231.      * 参 数:    $table 表名(必填)
  232.                 $data 待添加数据,推荐使用数组类型(必填)
  233.                 $values 待添加数据值,如果为字符串时使用(选填)
  234.      * 返回值:    布尔
  235.      * 实 例:    $DB->addData('mydb',array('user'=>'admin','password'=>'123456','age'=>'18') 数组类型(提示: 这里可以直接用$_POST或者$_GET)
  236.                 $DB->addData('mydb','`user`,`password`,`age`',"'admin','123456','18'" 字符串类型
  237.     -------------------------------------------------------------------*/
  238.     public function addData($table = '', $data = array(), $values = '') {
  239.         if (empty($table)) {
  240.             $this->showError('待添加数据表名为空');
  241.         }
  242.         $table = '`'.strtr($table, array(' ' => '', '.' => '`.`', ',' => '`, `')).'`';
  243.         if (empty($data)) {
  244.             $this->showError('待添加数据为空');
  245.         }
  246.         if (is_array($data)) {
  247.             $values = '';
  248.             foreach ($data as $key => $val) {
  249.                 $key = trim($key);
  250.                 if (!empty($key)) {
  251.                     $fileds .= "`{$key}`,";
  252.                     $values .= $val ? "'".mysql_escape_string($val)."'," : '"",';
  253.                 }
  254.             }
  255.             $fileds = rtrim($fileds, ',');
  256.             $values = rtrim($values, ',');
  257.         } else {
  258.             $fileds = $data;
  259.         }
  260.         return $this->query("INSERT INTO {$table} ({$fileds}) VALUES ({$values})");
  261.     }

  262.     /*------------------------------------------------------------------
  263.      * 函数名:    setData($table, $data, $condition, $unQuot)
  264.      * 作 用:    更改数据
  265.      * 参 数:    $table 表名(必填)
  266.                 $data 待更改数据,可以为数组(必填)
  267.                 $condition 更改条件(选填)
  268.                 $unQuot 不需要加引号的字段,用于字段的加减运算等情况,多个字段用,分隔或者写入一个数组(选填)
  269.      * 返回值:    布尔
  270.      * 实 例:    $DB->setData('mydb',array('user'=>'admin','password'=>'123456','WHERE id=1') 数组类型
  271.                 $DB->setData('mydb',"user='admin',password='123456'",'WHERE id=1') 字符串类型
  272.     -------------------------------------------------------------------*/
  273.     public function setData($table = '', $data = '', $condition = '', $unQuot = array()) {
  274.         if (empty($table)) {
  275.             $this->showError('待修改数据表名为空');
  276.         }
  277.         $table = '`'.strtr($table, array(' ' => '', '.' => '`.`', ',' => '`, `')).'`';
  278.         if (empty($data)) {
  279.             $this->showError('待修改数据为空');
  280.         }
  281.         if (is_array($data)) {
  282.             $unQuot = is_array($unQuot) ? $unQuot : explode(',', $unQuot);
  283.             foreach ($data as $key => $val) {
  284.                 $val = mysql_escape_string($val);
  285.                 $values .= '`'.$key.'`='.(in_array($key, $unQuot) ? "{$val}," : "'{$val}',");
  286.             }
  287.             $values = rtrim($values, ',');
  288.         } else {
  289.             $values = $data;
  290.         }
  291.         return $this->query("UPDATE {$table} SET {$values} {$condition}");
  292.     }

  293.     /*------------------------------------------------------------------
  294.      * 函数名:    delData($table, $condition)
  295.      * 作 用:    删除数据
  296.      * 参 数:    $table 表名(必填)
  297.                  $condition 删除条件(选填)
  298.      * 返回值:    布尔
  299.      * 实 例:    $DB->delData('mydb','id=1')
  300.     -------------------------------------------------------------------*/
  301.     public function delData($table, $condition = '') {
  302.         $table = '`'.strtr($table, array(' ' => '', '.' => '`.`', ',' => '`, `')).'`';
  303.         return $this->query("DELETE FROM {$table}".($condition ? " WHERE {$condition}" : ''));
  304.     }

  305.     /*------------------------------------------------------------------
  306.      * 函数名:    fetch($result, $type, $arrType)
  307.      * 作 用:    根据从结果集取得的行生成数组
  308.      * 参 数:    $result 结果集(选填)
  309.                  $type 返回的数组类型,1为mysql_fetch_assoc,2为mysql_fetch_row,3为mysql_fetch_object,默认为mysql_fetch_array(选填)
  310.                 $arrType 用于mysql_fetch_array,可以接受以下值: MYSQL_ASSOC,MYSQL_NUM 和 MYSQL_BOTH(选填)
  311.      * 返回值:    布尔
  312.      * 实 例:    无
  313.     -------------------------------------------------------------------*/
  314.     public function fetch($result = '', $type = '', $arrType = MYSQL_BOTH) {
  315.         if (empty($result)) {
  316.             $result = $this->result;
  317.         }
  318.         if (!$result) {
  319.             $this->showError('未获取到查询结果', true);
  320.         }
  321.         switch ($type) {
  322.             case 1: // 获取关联数组,使用$row['字段名']
  323.                 return mysql_fetch_assoc($result);
  324.             case 2: // 获取数字索引数组,使用$row[0],$row[1],$row[2]
  325.                 return mysql_fetch_row($result);
  326.             case 3: // 获取对象数组
  327.                 return mysql_fetch_object($result);
  328.             default: // 关联数组,或数字数组,或二者兼有
  329.                 return mysql_fetch_array($result, $arrType);
  330.         }
  331.     }

  332.     // 取得结果数据
  333.     public function result($result = '', $rows = 0, $field = '') {
  334.         if (empty($result)) {
  335.             $result = $this->result;
  336.         }
  337.         if (!$result) {
  338.             $this->showError('未获取到查询结果', true);
  339.         }
  340.         return mysql_result($result, $rows, $field);
  341.     }
复制代码







上一篇:简单的上传类
下一篇:[转载] 一个PHPer的面试经历
authicon  楼主| kooness 发表于 2010-12-3 19:07:07 | 显示全部楼层
本帖最后由 kooness 于 2010-12-3 19:25 编辑
  1.     /*------------------------------------------------------------------
  2.     函数名:    numFields($result)
  3.     作 用:    查询字段数量
  4.     参 数:    $result 结果集(选填)
  5.     返回值:    字符串
  6.     实 例:    $DB->num_fields("mydb")
  7.     -------------------------------------------------------------------*/
  8.     public function numFields($result = '') {
  9.         if (empty($result)) {
  10.             $result = $this->result;
  11.         }
  12.         if (!$result) {
  13.             $this->showError('未获取到查询结果', true);
  14.         }
  15.         return mysql_num_fields($result);
  16.     }

  17.     // 根据select查询结果计算结果集条数
  18.     public function numRows($result = '') {
  19.         if (empty($result)) {
  20.             $result = $this->result;
  21.         }
  22.         if (!$result) {
  23.             $this->showError('未获取到查询结果', true);
  24.         }
  25.         $rows = mysql_num_rows($result);
  26.         $this->numRows = $rows > 0 ? $rows : 0;
  27.         return $this->numRows;
  28.     }

  29.     // 根据insert,update,delete执行结果取得影响行数
  30.     public function affectedRows() {
  31.         return mysql_affected_rows();

  32.     }

  33.     // 取得上一步INSERT 操作产生的ID
  34.     public function insertId() {
  35.         return mysql_insert_id();
  36.     }

  37.     // 指向确定的一条数据记录
  38.     public function dataSeek($result, $id = 0) {
  39.         if (empty($result)) {
  40.             $result = $this->result;
  41.         }
  42.         if (!$result) {
  43.             $this->showError('未获取到查询结果', true);
  44.         }
  45.         if ($id > 0) {
  46.             $id = $id - 1;
  47.         }
  48.         if (!mysql_data_seek($this->result, $id)) {
  49.             $this->showError('指定的数据不存在');
  50.         }
  51.         return $this->result;
  52.     }

  53.     /*------------------------------------------------------------------
  54.      * 函数名:    getQuery($unset)
  55.      * 作 用:    获取地址栏参数,主要用于分页时传递地址栏其它参数
  56.      * 参 数:    $unset 不需要传递的参数,多个参数请用英文逗号分隔(选填)
  57.      * 返回值:    字符串
  58.      * 实 例:    getQuery('page,sort')
  59.     -------------------------------------------------------------------*/
  60.     public function getQuery($unset = '') {
  61.         $list = array();
  62.         $keys = explode(',', $unset);
  63.         foreach ($_GET as $key => $val) {
  64.             if (!in_array($key, $keys)) {
  65.                 $list[] = $key.'='.urlencode($val);
  66.             }
  67.         }
  68.         return implode('&', $list);
  69.     }

  70.     /*------------------------------------------------------------------
  71.      * 函数名:    getPage($table, $fileds, $condition, $pageSize)
  72.      * 作 用:    获取分页信息
  73.      * 参 数:    $table 表名(必填)
  74.                 $fileds 字段名,默认所有字段(选填)
  75.                 $condition 查询条件(选填)
  76.                 $pageSize 每页显示记录条数,默认10条(选填)
  77.      * 返回值:    字符串(总记录条数)
  78.      * 实 例:    $total = $DB->getPage('guestbook', '', 'ORDER BY id DESC', 15);
  79.                 if ($total > 0) {
  80.                     while ($row = $DB->fetch()) {
  81.                         // ......
  82.                     }
  83.                     echo $DB->showPage();
  84.                 } else {
  85.                     echo '无数据';
  86.                 }
  87.     -------------------------------------------------------------------*/
  88.     public function getPage($table, $fileds = '', $condition = '', $pageSize = 10) {
  89.         $table = '`'.strtr($table, array(' ' => '', '.' => '`.`', ',' => '`, `')).'`';
  90.         if (empty($fileds)) {
  91.             $fileds = '*';
  92.         }
  93.         $this->query("SELECT * FROM {$table} {$condition}");
  94.         $this->numRows();
  95.         if ($this->numRows > 0) {
  96.             if (intval($pageSize) > 0) {
  97.                 $this->pageSize = intval($pageSize);
  98.             }
  99.             $this->pageNow = isset($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
  100.             $this->pageAll = ceil($this->numRows / $this->pageSize);
  101.             if ($this->pageNow > $this->pageAll) {
  102.                 $this->pageNow = $this->pageAll;
  103.             }
  104.             $this->query("SELECT {$fileds} FROM {$table} {$condition}".$this->limit(true));
  105.         }
  106.         return $this->numRows;
  107.     }

  108.     // 构造分页limit语句,和getPage()函数搭配使用.
  109.     public function limit($str = false) {
  110.         $offset = ($this->pageNow-1) * $this->pageSize;
  111.         return $str ? ' LIMIT '.$offset.','.$this->pageSize : $offset;
  112.     }

  113.     // 显示分页,必须和getPage()函数搭配使用,$number=true表示显示数字分页,否则只显示首页、上页、下页、尾页.
  114.     public function showPage($number = true) {
  115.         $pageBar = '';
  116.         if ($this->pageAll > 1) {
  117.             $pageBar .= '<ul class="page">';
  118.             $url = $this->getQuery('page');
  119.             $url = empty($url) ? '?page=' : '?'.$url.'&page=';
  120.             if ($this->pageNow > 1) {
  121.                 $pageBar .= '<li><a href="'.$url.'1">首页</a></li>';
  122.                 $pageBar .= '<li><a href="'.$url.($this->pageNow-1).'">上页</a></li>';
  123.             } else {
  124.                 $pageBar .= '<li class="stop"><span>首页</span></li>';
  125.                 $pageBar .= '<li class="stop"><span>上页</span></li>';
  126.             }
  127.             if ($number) {
  128.                 if ($this->pageAll < 6) {
  129.                     $arr = range(1, $this->pageAll);
  130.                 } else {
  131.                     if ($this->pageNow < 3) {
  132.                         $arr = range(1, 5);
  133.                     } elseif ($this->pageNow <= $this->pageAll && $this->pageNow > ($this->pageAll - 3)) {
  134.                         $arr = range(($this->pageAll - 4), $this->pageAll);
  135.                     } else {
  136.                         $arr = range(($this->pageNow - 2), ($this->pageNow + 2));
  137.                     }
  138.                 }
  139.                 foreach ($arr as $val) {
  140.                     if ($val == $this->pageNow) {
  141.                         $pageBar .= '<li class="curr"><span>'.$val.'</span></li>';
  142.                     } else {
  143.                         $pageBar .= '<li><a href="'.$url. $val.'">'.$val.'</a></li>';
  144.                     }
  145.                 }
  146.             }
  147.             if ($this->pageNow < $this->pageAll) {
  148.                 $pageBar .= '<li><a href="'.$url.($this->pageNow + 1).'">下页</a>';
  149.                 $pageBar .= '<li><a href="'.$url.$this->pageAll.'">尾页</a></li>';
  150.             } else {
  151.                 $pageBar .= '<li class="stop"><span>下页</span></li>';
  152.                 $pageBar .= '<li class="stop"><span>尾页</span></li>';
  153.             }
  154.             $pageBar .= '<li class="stop"><span>';
  155.             $pageBar .= "页次:{$this->pageNow}/{$this->pageAll} {$this->pageSize}条/页 总记录:{$this->numRows} 转到:";
  156.             $pageBar .= "<input id="page" value="{$this->pageNow}" type="text" onblur="goPage('{$url}',{$this->pageAll});" />";
  157.             $pageBar .= '</span></li></ul>';
  158.         }
  159.         return $pageBar;
  160.     }

  161.     // 获得客户端真实的IP地址
  162.     public function getIP() {
  163.         if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
  164.             return $_SERVER['HTTP_X_FORWARDED_FOR'];
  165.         } elseif ($_SERVER['HTTP_CLIENT_IP']) {
  166.             return $_SERVER['HTTP_CLIENT_IP'];
  167.         } elseif ($_SERVER['REMOTE_ADDR']) {
  168.             return $_SERVER['REMOTE_ADDR'];
  169.         } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
  170.             return getenv('HTTP_X_FORWARDED_FOR');
  171.         } elseif (getenv('HTTP_CLIENT_IP')) {
  172.             return getenv('HTTP_CLIENT_IP');
  173.         } elseif (getenv('REMOTE_ADDR')) {
  174.             return getenv('REMOTE_ADDR');
  175.         }
  176.         return '';
  177.     }

  178.     /*------------------------------------------------------------------
  179.      * 函数名:    makeSql($table)
  180.      * 作 用:    从数据表读取信息并生成SQL语句
  181.      * 参 数:    $table 待读取的表名(必填)
  182.      * 返回值:    字符串
  183.      * 实 例:    无
  184.     -------------------------------------------------------------------*/
  185.     public function makeSql($table = '') {
  186.         if (empty($table)) {
  187.             $this->showError('待读取表名为空');
  188.         }
  189.         $result = $this->query("SHOW CREATE TABLE `{$table}`");
  190.         $row     = $this->fetch($result, 2);
  191.         $sqlStr = '';
  192.         if ($row) {
  193.             $sqlStr .= "-- --------------------------------------------\r\n";
  194.             $sqlStr .= "-- Table structure for `{$table}`\r\n";
  195.             $sqlStr .= "-- --------------------------------------------\r\n";
  196.             $sqlStr .= "DROP TABLE IF EXISTS `{$table}`;\r\n{$row[1]};\r\n";
  197.             $this->getData($table);
  198.             $fields = $this->numFields();
  199.             $sqlStr .= "\r\n";
  200.             if ($this->numRows() > 0) {
  201.                 $sqlStr .= "-- --------------------------------------------\r\n";
  202.                 $sqlStr .= "-- Records of `{$table}`\r\n";
  203.                 $sqlStr .= "-- --------------------------------------------\r\n";
  204.                 while ($row  = $this->fetch('', 2)) {
  205.                     $sqlStr .= "INSERT INTO `{$table}` VALUES (";
  206.                     for ($i  = 0; $i < $fields; $i++) {
  207.                         $sqlStr .= "'".mysql_escape_string($row[$i])."',";
  208.                     }
  209.                     $sqlStr = rtrim($sqlStr, ',').");\r\n";
  210.                 }
  211.             }
  212.         }
  213.         return $sqlStr;
  214.     }

  215.     /*------------------------------------------------------------------
  216.      * 函数名:    readSql($filePath)
  217.      * 作 用:    读取SQL文件并过滤注释
  218.      * 参 数:    $filePath SQL文件路径(必填)
  219.      * 返回值:    字符串(错误信息) or 数组
  220.      * 实 例:    无
  221.     -------------------------------------------------------------------*/
  222.     public function readSql($filePath) {
  223.         if (!file_exists($filePath)) {
  224.             $this->showError($filePath.'不存在');
  225.         }
  226.         $sql = file_get_contents($filePath);
  227.         if (empty($sql)) {
  228.             $this->showError($filePath.'中无有效数据');
  229.         }
  230.         // 过滤注释,并将两个以上的连续空格替换为一个
  231.         $sql = preg_replace(array('/\/\*.*\*\//s', '/(^|\s)+--.*/', '/ {2,}/'), array('', '', ' '), $sql);
  232.         $sql = preg_split('/;[\n\r]+/', $sql, -1, PREG_SPLIT_NO_EMPTY);
  233.         return array_map('trim', $sql);
  234.     }

  235.     /*------------------------------------------------------------------
  236.      * 函数名:    saveSql($sqlPath, $table)
  237.      * 作 用:    将当前数据库信息保存为SQL文件,可以分段保存(主要用于数据量比较大的数据库)
  238.      * 参 数:    $sqlPath SQL文件保存路径,如果为空则自动以当前日期为文件名并保存到当前目录(选填)
  239.                  $table 待保存的表名,多个表请用数组,为空表示保存所有表信息(选填)
  240.                 $rows 多少条语句为一段,为0则不分段。
  241.      * 返回值:    字符串
  242.      * 实 例:    $DB->saveSql('../mydb.sql');
  243.     -------------------------------------------------------------------*/
  244.     public function saveSql($sqlPath = '', $table = '', $rows = 0) {
  245.         $sql = '';
  246.         if (!is_array($table)) {
  247.             $table = empty($table) ? $this->listTables($this->data) : array($table);
  248.         }
  249.         foreach ($table as $tb){
  250.             $sql .= $this->makeSql($tb);
  251.         }
  252.         if (empty($sql)) {
  253.             return false;
  254.         }
  255.         $text  = "/******************************************************************\r\n";
  256.         $text .= "  Database: {$this->data}\r\n";
  257.         $text .= "  Date Created: ".date('Y-m-d H: i: s')."\r\n";
  258.         $text .= "*******************************************************************/\r\n\r\n";
  259.         $text .= $sql;
  260.         $info  = pathinfo($sqlPath);
  261.         $dirs  = $info['dirname'];
  262.         if (empty($info['extension'])) {
  263.             $dirs = empty($sqlPath) ? '' : rtrim($sqlPath, '/').'/';
  264.             $sqlPath = $dirs.date('YmdHis').'.sql';
  265.         }
  266.         $this->makeDirs($dirs);
  267.         if ($rows > 0) {
  268.             $sql  = preg_split('/;[\r\n]+/', $text, -1, PREG_SPLIT_NO_EMPTY);
  269.             $sql  = array_chunk($sql, $rows);
  270.             $num  = 1;
  271.             $ext  = pathinfo($sqlPath, PATHINFO_EXTENSION);
  272.             $path = rtrim($sqlPath, ".$ext");
  273.             foreach ($sql as $str) {
  274.                 $file = $path.'('.$num++.').'.$ext;
  275.                 $link = fopen($file, 'w+');
  276.                 fwrite($link, implode(";\r\n", $str).";\r\n");
  277.                 fclose($link);
  278.             }
  279.         } else {
  280.             $link = fopen($sqlPath, 'w+');
  281.             fwrite($link, $text);
  282.             fclose($link);
  283.         }
  284.     }

  285.     /*------------------------------------------------------------------
  286.      * 函数名:    loadSql($filePath)
  287.      * 作 用:    将SQL文件信息导入到数据库
  288.      * 参 数:    $sqlFile SQL文件路径(必填)
  289.      * 返回值:    字符串(未成功执行的sql语句)
  290.      * 实 例:    $DB->loadSql('../mydb.sql');
  291.     -------------------------------------------------------------------*/
  292.     public function loadSql($sqlFile = '') {
  293.         if (empty($sqlFile)) {
  294.             $this->showError('SQL文件路径为空');
  295.         }
  296.         $err_list = '';
  297.         $info = $this->readSql($sqlFile);
  298.         foreach ($info as $sql) {
  299.             if (@mysql_query($sql)) {
  300.                 $err_list .= $sql.'<br />';
  301.             }
  302.         }
  303.         return empty($err_list) ? '' : '下列语句执行失败:<br />'.$err_list;
  304.     }

  305.     // 自动建立多级目录,主要是为了给错误日志和导出SQL文件提供支持.
  306.     public function makeDirs($dirs = '', $mode = '0777') {
  307.         $dirs = strtr(trim($dirs), '\\', '/');
  308.         if (!empty($dirs) && !is_dir($dirs)) {
  309.             $this->makeDirs(dirname($dirs));
  310.             if (!mkdir($dirs, $mode)) {
  311.                 $this->showError('建立目录'.$dirs.'失败,请尝试手动建立!');
  312.             }
  313.         }
  314.     }

  315.     /*------------------------------------------------------------------
  316.      * 函数名:    showError($msg, $sql)
  317.      * 作 用:    输出显示错误信息
  318.      * 参 数:    $msg 错误信息(必填)
  319.                 $sql 是否显示错误的SQL语句,在SQL语句错误时使用(选填)
  320.      * 返回值: 字符串
  321.      * 实 例: 无
  322.     -------------------------------------------------------------------*/
  323.     public function showError($msg = '', $sql = false) {
  324.         $err='['.mysql_errno().']'.mysql_error();
  325.         if ($sql) {
  326.             $sql = 'SQL 语句: '.$this->sql;
  327.         }
  328.         if ($this->errLog == 'on') {
  329.             $dir = rtrim($this->errDir, '/');
  330.             $this->makeDirs($dir);
  331.             $filePath = $dir.'/'.date('Y-m-d').'.log';
  332.             $log  = "错误事件: {$msg}\r\n";
  333.             $log .= "错误原因: {$err}\r\n";
  334.             $log .= $sql ? "{$sql}\r\n" : '';
  335.             $log .= "客户端IP: ".$this->getIP()."\r\n";
  336.             $log .= "记录时间: ".date('Y/m/d H:i:s')."\r\n\r\n";
  337.             $log  = '错误日志: __'.(error_log($log, 3, $filePath) ? '此错误信息已被自动记录到日志'.$filePath : '写入错误信息到日志失败');
  338.         }
  339.         if ($this->errTip == 'on') {
  340.             $tip  = '<fieldset class="errlog">';
  341.             $tip .= '<legend>错误信息提示</legend>';
  342.             $tip .= '<label class="tip">错误事件: '.$err.'</label>';
  343.             $tip .= '<label class="msg">错误原因: '.$msg.'</label>';
  344.             $tip .= '<label class="sql">'.$sql.'</label>';
  345.             $tip .= '<label class="log">'.$log.'</label>';
  346.             $tip .= '</fieldset>';
  347.             die ($tip);
  348.         }
  349.     }

  350.     // 释放结果集
  351.     public function free($result = '') {
  352.         if (empty($result)) {
  353.             $result = $this->result;
  354.         }
  355.         @mysql_free_result($result);
  356.     }

  357.     // 关闭数据库
  358.     public function close($conn = '') {
  359.         if (empty($conn)) {
  360.             $conn = $this->conn;
  361.         }
  362.         @mysql_close($conn);
  363.     }

  364.     // 析构函数,自动释放结果集、关闭数据库,垃圾回收机制
  365.     public function __destruct() {
  366.         $this->free();
  367.         $this->close();
  368.     }
  369. }
  370. ?>
复制代码


authicon  楼主| kooness 发表于 2010-12-3 19:21:50 | 显示全部楼层
authicon qqoxygen 发表于 2011-6-17 10:59:37 | 显示全部楼层
真的有意思!
authicon TRACYFLYING 发表于 2011-6-17 18:00:05 | 显示全部楼层
顶的就是你
authicon Cute宝贝儿 发表于 2011-6-20 00:00:04 | 显示全部楼层
这个还是不错的!
authicon lilac_yao 发表于 2011-6-21 08:59:40 | 显示全部楼层
很好的,我喜欢
authicon 福倒菜菜子 发表于 2011-6-22 14:59:43 | 显示全部楼层
看一下啊,嘻嘻
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 21:58

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表