MYSQL操作类, 连贯操作, 缓存

 连贯操作

$db->table('news')->join('as n comment as m on n.id=m.nid ')->where('n.id=1')->find();

 

缓存

$db->table('news')->cache()->findAll(); 

 

代码
  1 <?php
  2 /**
  3  +----------------------------------------------------------
  4  * xiaokai Mysql操作类
  5  +----------------------------------------------------------
  6  * 文件名称  Db.class.php
  7  +----------------------------------------------------------
  8  * 文件描述  mysql操作类
  9  +----------------------------------------------------------
 10  * 作    者  xiaokai<myxiaokai@gmail.com>
 11  +----------------------------------------------------------
 12  * 时    间  2009-11-17
 13  +----------------------------------------------------------
 14  */
 15 
 16 class Db
 17 {
 18 
 19         //数据库连接标识
 20         protected $link         = null;
 21 
 22         //当前操作的表
 23         public    $table        = '';
 24 
 25         //查询参数
 26         protected $options      = array();
 27 
 28         //当前执行的SQL语句
 29         protected $sql          = '';
 30 
 31         //数据库查询次数
 32         protected $queryCount   = 0;
 33 
 34         //缓存次数
 35         protected $cacheCount   = 0;
 36 
 37         //缓存路径
 38         protected $cachePath    = '';
 39 
 40         //数据返回类型, 1代表数组, 2代表对象
 41         protected $returnType   = 1;
 42 
 43         /**
 44          * 连接数据库
 45          *
 46          * @access      public
 47          * @param       array    $db  数据库配置
 48          * @return      resource 数据库连接标识
 49          */
 50         public function connect($db)
 51         {
 52                 //根据配置使用不同函数连接数据库
 53                 $db['host'= isset($db['port']) ? $db['host'. ':' . $db['port': $db['host'];
 54                 $func = $db['pconnect'? 'mysql_pconnect' : 'mysql_connect';
 55                 $this->link = $func($db['host'], $db['user'], $db['pwd']);
 56                 mysql_select_db($db['database'], $this->link);
 57                 mysql_query("SET NAMES '{$db['char']}'");
 58                 $this->cachePath = isset($db['cachepath']) ? $db['cachepath': './';
 59                 return $this->link;
 60         }
 61 
 62 
 63 
 64         /**
 65          * 查询符合条件的一条记录
 66          *
 67          * @access      public
 68          * @param       string    $where  查询条件
 69          * @param       string    $field  查询字段
 70          * @param       string    $table  表
 71          * @return      mixed             符合条件的记录
 72          */
 73         public function find($where = NULL, $field = '*', $table = '')
 74         {
 75              return $this->findAll($where = NULL, $field = '*', $table = '', FALSE);
 76         }
 77 
 78 
 79 
 80         /**
 81          * 查询符合条件的所有记录
 82          *
 83          * @access      public
 84          * @param       string    $where  查询条件
 85          * @param       string    $field  查询字段
 86          * @param       string    $table  表
 87          * @return      mixed             符合条件的记录
 88          */
 89         public function findAll($where = NULL, $field = '*', $table = '', $all = TRUE)
 90         {
 91                 $this->options['where'= is_null($where? $this->options['where': $where;
 92                 $this->options['field'= isset($this->options['field']) ? $this->options['field': $field;
 93                 $this->options['table'= $table == '' ?  $this->table : $table;
 94                 $sql   = "SELECT {$this->options['field']} FROM `{$this->options['table']}` ";
 95                 $sql  .= isset($this->options['join']) ? ' LEFT JOIN ' . $this->options['join': '';
 96                 $sql  .= isset($this->options['where']) ? ' WHERE ' . $this->options['where': '';
 97                 $sql  .= isset($this->options['group']) ? ' GROUP BY ' . $this->options['group': '';
 98                 $sql  .= isset($this->options['having']) ? ' HAVING ' . $this->options['having': '';
 99                 $sql  .= isset($this->options['order']) ? ' ORDER BY ' . $this->options['order': '';
100                 $sql  .= isset($this->options['limit']) ? ' LIMIT ' . $this->options['limit': '';
101                 $this->sql = $sql;
102                 $row    = NULL;
103 
104                 //如果开启了缓存, 那么重缓存中获取数据
105                 if($this->options['cache'=== TRUE)
106                 {
107                         $row = $this->readCache();
108                 }
109 
110                 //如果读取失败, 或则没有开启缓存
111                 if(is_null($row))
112                 {
113                         $result = $this->query();
114                         $row    = $all === TRUE ? $this->fetchAll($result: $this->fetch($result);
115                         if($this->options['cache'=== TRUE)
116                                 //如果开启了缓存, 那么就写入
117                                 $this->writeCache($row);
118                         $this->options = array();
119                 }
120 
121                 return $row;
122         }
123 
124 
125 
126         /**
127          * 读取结果集中的所有记录到数组中
128          *
129          * @access public
130          * @param  resource  $result  结果集
131          * @return array
132          */
133         public function fetchAll($result = NULL)
134         {
135                 $rows = array();
136                 while($row = $this->fetch($result))
137                 {
138                         $rows[] = $row;
139                 }
140                 return $rows;
141         }
142 
143 
144 
145 
146         /**
147          * 读取结果集中的一行记录到数组中
148          *
149          * @access public
150          * @param  resource  $result  结果集
151          * @param  int       $type    返回类型, 1为数组, 2为对象
152          * @return mixed              根据返回类型返回
153          */
154         public function fetch($result = NULL, $type = NULL)
155         {
156                 $result = is_null($result? $this->result : $result;
157                 $type   = is_null($type)   ? $this->returnType : $type;
158                 $func   = $type === 1 ? 'mysql_fetch_assoc' : 'mysql_fetch_object';
159                 return $func($result);
160         }
161 
162 
163 
164         /**
165          * 执行SQL命令
166          *
167          * @access      public
168          * @param       string    $sql    SQL命令
169          * @param       resource  $link   数据库连接标识
170          * @return      mixed             数据库结果集
171          */
172         public function query($sql = '', $link = NULL)
173         {
174                 $this->queryCount++;
175                 $sql = empty($sql? $this->sql : $sql;
176                 $link = is_null($link? $this->link : $link;
177                 $this->result = mysql_query($sql, $link);
178                 if(is_resource($this->result))
179                 {
180                         return $this->result;
181                 }
182                 //如果执行SQL出现错误, 那么抛出异常
183                 exit('<strong>Mysql error:</strong>' . $this->getError());
184         }
185 
186 
187 
188         /**
189          * 执行SQL命令
190          *
191          * @access      public
192          * @param       string    $sql    SQL命令
193          * @param       resource  $link   数据库连接标识
194          * @return      bool              是否执行成功
195          */
196         public function execute($sql = '', $link = NULL)
197         {
198                 $this->queryCount++;
199                 $sql = empty($sql? $this->sql : $sql;
200                 $link = is_null($link? $this->link : $link;
201                 if(mysql_query($sql, $link))
202                 {
203                         return TRUE;
204                 }
205                 return FALSE;
206         }
207 
208 
209 
210         /**
211          * 插入记录
212          *
213          * @access public
214          * @param  array  $data  插入的记录, 格式:array('字段名'=>'值', '字段名'=>'值');
215          * @param  string $table 表名
216          * @return bool          当前记录id
217          */
218         public function add($data, $table = NULL)
219         {
220                 $table = is_null($table? $this->table : $table;
221                 $sql   = "INSERT INTO `{$table}`";
222                 $fields = $values = array();
223                 $field = $value = '';
224                 //遍历记录, 格式化字段名称与值
225                 foreach($data as $key => $val)
226                 {
227                         $fields[] = "`{$table}`.`{$key}`";
228                         $values[] = is_numeric($val? $val : "'{$val}'";
229                 }
230                 $field = join(',', $fields);
231                 $value = join(',', $values);
232                 unset($fields, $values);
233                 $sql .= "({$field}) VALUES({$value})";
234                 $this->sql = $sql;
235                 $this->execute();
236                 return $this->insertId();
237         }
238 
239 
240 
241         /**
242          * 删除记录
243          *
244          * @access public
245          * @param  string  $where  条件
246          * @param  string  $table  表名
247          * @return bool            影响行数
248          */
249         public function delete($where = NULL, $table = NULL)
250         {
251                 $table = is_null($table? $this->table : $table;
252                 $where = is_null($where? $this->options['where': $where;
253                 $sql   = "DELETE FROM `{$table}` WHERE {$where}";
254                 $this->sql = $sql;
255                 $this->execute();
256                 return $this->affectedRows();
257         }
258 
259 
260 
261         /**
262          * 更新记录
263          *
264          * @access public
265          * @param  array   $data   更新的数据 格式:array('字段名' => 值);
266          * @param  string  $where  更新条件
267          * @param  string  $table  表名
268          * @return bool            影响多少条信息
269          */
270         public function update($data, $where = NULL, $table = NULL)
271         {
272                 $table  = is_null($table? $this->table : $table;
273                 $where  = is_null($where? $this->options['where': $where;
274                 $sql    = "UPDATE `{$table}` SET ";
275                 $values = array();
276                 foreach($data as $key => $val)
277                 {
278                         $val      = is_numeric($val? $val : "'{$val}'";
279                         $values[] = "`{$table}`.`{$key}` = {$val}";
280                 }
281                 $value = join(',', $values);
282                 $this->sql = $sql . $value . " WHERE {$where}";
283                 $this->execute();
284                 return $this->affectedRows();
285 
286         }
287 
288 
289 
290         /**
291          * 缓存当前查询
292          *
293          * @access      public
294          * @param       string    $name   缓存名称
295          * @param       int       $time   缓存有效时间, 默认为60秒
296          * @param       string    $path   缓存文件存放路径
297          * @return      object            数据库操作对象
298          */
299         public function cache($name = '', $time = 60, $path = '')
300         {
301                 $this->options['cache']         = TRUE;
302                 $this->options['cacheTime']     = $time;
303                 $this->options['cacheName']     = empty($name? md5($this->sql) : $name;
304                 $this->options['cachePath']     = empty($path? $this->cachePath : $path;
305                 return $this;
306         }
307 
308 
309 
310 
311         /**
312          * 读取缓存
313          *
314          * @access      public
315          * @return      mixed   如果读取成功返回缓存内容, 否则返回NULL
316          */
317         protected function readCache()
318         {
319                 $file = $this->options['cachePath'. $this->options['cacheName'. '.php';
320                 if(file_exists($file))
321                 {
322                         //缓存过期
323                         if((filemtime($file+ $this->options['cacheTime']) < time())
324                         {
325                                 @unlink($file);
326                                 return NULL;
327                         }
328 
329                         if(1 === $this->returnType)
330                         {
331                                 $row = include $file;
332                         }
333                         else
334                         {
335                                 $data = file_get_contents($file);
336                                 $row  = unserialize($data);
337                         }
338                         return $row;
339                 }
340                 return NULL;
341         }
342 
343 
344 
345         /**
346          * 写入缓存
347          *
348          * @access      public
349          * @param       mixed   $data   缓存内容
350          * @return      bool            是否写入成功
351          */
352         public function writeCache($data)
353         {
354                 $this->cacheCount++;
355                 $file = $this->options['cachePath'. $this->options['cacheName'. '.php';
356                 if(1 === $this->returnType)
357                         $data = '<?php return ' . var_export($data, TRUE. '; ?>';
358                 else
359                         $data = serialize($data);
360                 return file_put_contents($file, $data);
361         }
362 
363 
364 
365         //自动加载函数, 实现特殊操作
366         public function __call($func, $args)
367         {
368                 if(in_array($func, array('field', 'join', 'where', 'order', 'group', 'limit', 'having')))
369                 {
370                         $this->options[$func= array_shift($args);
371                         return $this;
372                 }
373                 elseif($func === 'table')
374                 {
375                         $this->options['table'= array_shift($args);
376                         $this->table            = $this->options['table'];
377                         return $this;
378                 }
379                 //如果函数不存在, 则抛出异常
380                 exit('Call to undefined method Db::' . $func . '()');
381         }
382 
383         //返回上一次操作所影响的行数
384         public function affectedRows($link = null)
385         {
386                 $link = is_null($link? $this->link : $link;
387                 return mysql_affected_rows($link);
388         }
389 
390         //返回上一次操作记录的id
391         public function insertId($link = null)
392         {
393                 $link = is_null($link? $this->link : $link;
394                 return mysql_insert_id($link);
395         }
396 
397         //清空结果集
398         public function free($result = null)
399         {
400                 $result = is_null($result? $this->result : $result;
401                 return mysql_free_result($result);
402         }
403 
404 
405         //返回错误信息
406         public function getError($link = NULL)
407         {
408                 $link = is_null($link? $this->link : $link;
409                 return mysql_error($link);
410         }
411 
412         //返回错误编号
413         public function getErrno($link = NULL)
414         {
415                 $link = is_null($link? $this->link : $link;
416                 return mysql_errno($link);
417         }
418 }
419 
420 // 文件结束  Db.class.php

 

 

 

 

posted on 2010-01-15 02:28  李恺  阅读(224)  评论(0)    收藏  举报